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); }