Jump to Real's How-to Main page

Remove spaces from a string

Remove all spaces
public String removeSpaces(String s) {
  StringTokenizer st = new StringTokenizer(s," ",false);
  String t="";
  while (st.hasMoreElements()) t += st.nextElement();
  return t;
  }

[JDK1.5]
The String trim() method returns a copy of the string, with leading and trailing whitespace omitted.

ref : http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#trim()

[JDK1.4]
Here a complete solution to remove leading or trailing spaces in a String using regular expressions.

import java.util.regex.*;

public class BlankRemover
{

    /* remove leading whitespace */
    public static String ltrim(String source) {
        return source.replaceAll("^\\s+", "");
    }

    /* remove trailing whitespace */
    public static String rtrim(String source) {
        return source.replaceAll("\\s+$", "");
    }

    /* replace multiple whitespaces between words with single blank */
    public static String itrim(String source) {
        return source.replaceAll("\\b\\s{2,}\\b", " ");
    }

    /* remove all superfluous whitespaces in source string */
    public static String trim(String source) {
        return itrim(ltrim(rtrim(source)));
    }

    public static String lrtrim(String source){
        return ltrim(rtrim(source));
    }

    public static void main(String[] args){
        String oldStr =
         ">     <1-2-1-2-1-2-1-2-1-2-1-----2-1-2-1-2-1-2-1-2-1-2-1-2>   <";
        String newStr = oldStr.replaceAll("-", " ");
        System.out.println(newStr);
        System.out.println(ltrim(newStr));
        System.out.println(rtrim(newStr));
        System.out.println(itrim(newStr));
        System.out.println(lrtrim(newStr));
    }


}
Thanks to jsanza for the tip!
If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]