Split a String in Java

Java String class has the method split() to split a string around matches of a given regular expression.

  • java.lang.String: public String[] split(String regex)
  • Parameters: regex – the delimiting regular expression
  • Returns: the array of strings computed by splitting this string around matches of the given regular expression
String str = "boo:and:foo";
String[] parts = str.split(":");  // { "boo", "and", "foo" }
String part1 = parts[0];          // "boo"
String part2 = parts[1];          // "and"

parts = str.split("o");           // { "b", "", ":and:f" }
// trailing empty strings are discarded

Note that, the delimiter is a regular expression; so escape special characters if necessary. For example,

  • split around period: str.split("\\.")
  • split around whitespace: str.split("\\s+")

Comments

comments