java: what's the most efficient way to remove all blank space from a StringBuilder

java

Solution

You shouldn't call `delete` more than once - simply move each character down to its final location and then delete the range at the end.

static void removeBlankSpace(StringBuilder sb) {
  int j = 0;
  for(int i = 0; i < sb.length; i++) {
    if (!Character.isWhitespace(sb.charAt(i))) {
       sb.setCharAt(j++, sb.charAt(i));
    }
  }
  sb.delete(j, sb.length);
}

Problem

I implement it by the following code, but I don't know whether there's a more efficient way to remove all blank spaces from a StringBuilder ``` private static StringBuilder removeBlankSpace(StringBuilder sb){ for(int i=0;i<sb.length();++i){ if(Character.isWhitespace(sb.charAt(i))){ sb.deleteCharAt(i); i--; } } return sb; } ```

Original source

Related problems