Real'sHowTo AddThis Feed Button
Custom Search

Remove spaces from a stringTag(s): String/Number


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.

public class BlankRemover {
  
    private 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("*" + BlankRemover.ltrim(newStr) + "*");
        System.out.println("*" + BlankRemover.rtrim(newStr) + "*");
        System.out.println("*" + BlankRemover.itrim(newStr) + "*");
        System.out.println("*" + BlankRemover.lrtrim(newStr) + "*");
    }
    /*
    output :
          [1 2 1 2 1 2 1 2 1 2 1     2 1 2 1 2 1 2 1 2 1 2 1 2]    
    *[1 2 1 2 1 2 1 2 1 2 1     2 1 2 1 2 1 2 1 2 1 2 1 2]    *
    *      [1 2 1 2 1 2 1 2 1 2 1     2 1 2 1 2 1 2 1 2 1 2 1 2]*
    *      [1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2]    *
    *[1 2 1 2 1 2 1 2 1 2 1     2 1 2 1 2 1 2 1 2 1 2 1 2]*
    
    */
}
Thanks to jsanza for the tip!
blog comments powered by Disqus


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-2014
[ home ]