It is necessary to make the string "aaaaabbbcccc dddddd" => "abc d". Thank you in advance.

  • one
    @vp_arth People who came from Google, with the same question, are not interested in "this is the author's work" or not. Unfortunately, this is a fairly common misconception about the goals of the site , even among experienced participants. Work for the author - jfs

2 answers 2

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
  • @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(); }