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 Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger