It is necessary to make the string "aaaaabbbcccc dddddd" => "abc d". Thank you in advance.
2 answers
public static void main (String[] args) throws Exception { String text = "aaaa111111111abbbccc........ dddddd"; text = text.replaceAll("(.)\\1+", "$1"); System.out.println(text); //a1abc. d } Found a solution here .
- It is a shame, comrade, to answer such questions. - user207618
- @Other you misunderstand what is useful and what is not on the site . Here's a comment for you also applies - jfs
- @jfs, this is an eternal problem. And disputes on this subject are not rare. The bottom line is that despite the desire to create a "clean and beautiful knowledge database," traffic prevails here. And on cleanliness to spit. - user207618
|
For example, it can be done like this:
String compact(final String s) { if (s == null || s.length() < 2) return s; final StringBuilder builder = new StringBuilder(s.length()); char c = s.charAt(0); builder.append(c); for (int i = 1; i < s.length(); ++i) { char ci = s.charAt(i); if (c != ci) { c = ci; builder.append(c); } } return builder.toString(); } |