Split a string using String.split()

The String class has a split() method, that will return a String array.

[JDK1.4]

public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      String s3 = "Real-How-To";
      String [] temp = null;
      temp = s3.split("-");
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}

/*
output :
------------
Real
How
To
------------
*/

split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression.

For example :

String s3 = "Real.How.To";
...
temp = s3.split("\\.");

or

String s3 = "Real|How|To";
...
temp = s3.split("\\|");
The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !
Consider this example
public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      String s = "Real|How|To|||";
      String [] temp = null;
      temp = s.split("\\|");
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}
/*
output :
------------
Real
How
To
------------
*/
The result does not include the empty strings between the "|" separator. To keep the empty strings :
public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      String s = "Real|How|To|||";
      String [] temp = null;
      temp = s.split("\\|", -1);
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}
/*
output :
------------
Real
How
To



------------
*/
See String.html#split(java.lang.String, int).
String.split() is only available since JDK 1.4.

With previous version, java.util.StringTokeniser can be used.

See this HowTo


Some notes from A. Gonzales about String.split()

An interesting thing about String.split():

"  s".split(" ")     -> {"","","s"}
"".split("" )        -> {""}
" ".split(" ")       -> {} (!)
"       ".split(" ") -> {} (!)
"  s ".split(" ")    -> {"","","s"} (!)

It's important to note that an invocation like:
param = req.getParam(...);
String[] words = param.split(" ");
String firstWord = words[0];
will generate a NullPointerException if param.equals(" ").
Using split() with a space can be a problem. Consider the following :
public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      // extra spaces
      String s3 = "Real  How To";
      String [] temp = null;
      temp = s3.split(" ");
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}
/*
output :
------------
Real

How
To
------------
*/
We have an extra element. The fix is to specify a regular expression to match one or more spaces.
public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      // extra spaces
      String s3 = "Real  How To";
      String [] temp = null;
      temp = s3.split("\\s+");
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}
/*
output :
------------
Real
How
To
------------
*/

Since String.split() is based on regular expression, you can make some complex operations with a simple call!
public class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  }

  public void doit() {
      String s3 = "{RealHowto}{java-0438.html}{usage of String.split()}";
      String[] temp = s3.split("[{}]");
      dump(temp);
  }

  public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
        System.out.println(s[i]);
    }
    System.out.println("------------");
  }
}

/*
output :
------------

RealHowto

java-0438.html

usage of String.split()
------------
note : extra element with empty string :-(
*/





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