How to remove extra spaces in a string if it is a StringBuffer ? It is important not to use the transition to the String .

let's say a string:

 StringBuffer str = new StringBuffer("this is а test message"); 

should turn into:

 "this is a test message" 

    1 answer 1

    Run through StringBuffer and move all non-whitespace characters to the beginning. If we encounter a space, and it goes first, also move it and remember the index. All subsequent spaces are ignored. When we meet a non-whitespace character, reset the space index.

     static void removeWhiteSpaces(StringBuffer sb) { int end = 0; int spaceIndex = -1; for (int i = 0; i < sb.length; i++) { if (!Character.isWhitespace(sb.charAt(i))) { sb.setCharAt(end++, sb.charAt(i)); spaceIndex = -1; } else if (spaceIndex < 0) { sb.setCharAt(end++, sb.charAt(i)); spaceIndex = i; } } sb.setLength(end); } 
    • one
      Instead of sb.delete(end, sb.length); you can use sb.setLength(end) , it will work a little faster. - OleGG
    • @ Olegg yes indeed. Updated the answer, thank you. - andreycha
    • @andreycha but, it removes all spaces, and I need to remove, if there are 2 or 3, for example. - thundermind
    • @thundermind you asked "How to remove extra spaces?", and where is their number? Explain the task in detail then. - andreycha
    • @andreycha, unfortunately the site erased the extra spaces in the example. The task is as follows: there is a string of type StringBuffer, and it is necessary to remove extra spaces, if there is more than one. - thundermind