Java: what is the most efficient way to remove all white space from a StringBuilder

I implement it with the following code, but I do not know if there is a more efficient way to remove all spaces from 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;
}
+3
source share
5 answers

You should not call deletemore than once - just move each character 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);
}
+10
source

EDIT: leaving this answer to posterity but Keith Randall O (n) solution is much nicer.

You may find it more efficient to work from the far end - this way, by the time you delete the earlier characters, you won't copy the spaces later.

, , delete, deleteCharAt. - :

private static StringBuilder removeBlankSpace(StringBuilder sb) {
    int currentEnd = -1;
    for(int i = sb.length() - 1; i >= 0; i--) {
        if (Character.isWhitespace(sb.charAt(i))) {
            if (currentEnd == -1) {
                currentEnd = i + 1;
            }
        } else {
            // Moved from whitespace to non-whitespace
            if (currentEnd != -1) {
                sb.delete(i + 1, currentEnd);
                currentEnd = -1;
            }
        }
    }
    // All leading whitespace
    if (currentEnd != -1) {
        sb.delete(0, currentEnd);
    }
    return sb;
}
+3

What about the following (assuming you initialized StringBuilder sb):

sb = new StringBuilder(sb.toString().replaceAll("\\s", ""));
+2
source

Code to remove trailing and trailing white spaces

 int i = 0;
 int j = 0;

 for (; i < whiteSpcaTest.length();) {
   i = 0;
   if (Character.isWhitespace(whiteSpcaTest.charAt(i))) {
     whiteSpcaTest.deleteCharAt(i);

   } else {
     break;
   }
 }
 for (; j >= 0;) {
   j = whiteSpcaTest.length() - 1;
   if (Character.isWhitespace(whiteSpcaTest.charAt(j))) {
     whiteSpcaTest.deleteCharAt(j);

   } else {
     break;
   }

 }
+1
source

The java string trim () method removes leading and trailing spaces. The space character value in Unicode is '\ u0020'. The trim () method in a java string checks this unicode value before and after the string, if it exists, removes spaces and returns a missing string. For instance:

public class StringTrimExample{  
public static void main(String args[]){  
String s1="  hello string   ";  
System.out.println(s1+"javatpoint");//without trim()  
System.out.println(s1.trim()+"javatpoint");//with trim()  
}}  

and results:

  hello string   javatpoint
hello stringjavatpoint  
0
source

All Articles