How to remove white-space from a String


/*** replace multiple whitespaces between words with single blank */

String before=" hi how are you ";
String value = before.trim().replaceAll("[ ][ ]*", " ");

or

String value = before.replaceAll("\\b\\s{2,}\\b", " ");

//before : hi how are you

//after: hi how are you

/* remove leading whitespace */

String value= before.replaceAll("^\\s+", "");

//before : hi how are you

//after: hi how are you

/* remove trailing whitespace */

String value= before.replaceAll("\\s+$", "");

//before : hi how are you

//after: hi how are you

/** Trims all white spaces from an input string. */

public String trimSpace(String s){
String[] trimString = s.trim().split(" ");
String trimmedString = "";
for (int i = 0; i < trimString.length; i++){
trimmedString = trimmedString + trimString[i];
}
return trimmedString;
}

Related Posts: