Returns a new string with all the whitespace removed in Java
Description
The following code shows how to returns a new string with all the whitespace removed.
Example
/* w w w.j av a 2 s .c o m*/
public class Main{
/**
* Returns a new string with all the whitespace removed
*
* @param s the source string
* @return the string without whitespace or null
*/
public static String removeWhiteSpace(String s)
{
String retn = null;
if (s != null)
{
int len = s.length();
StringBuffer sbuf = new StringBuffer(len);
for (int i = 0; i < len; i++)
{
char c = s.charAt(i);
if (!Character.isWhitespace(c))
sbuf.append(c);
}
retn = sbuf.toString();
}
return retn;
}
public static void main(String[] argv){
System.out.println(removeWhiteSpace("from java2s.c o m"));
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »