Split a string in Java

Split a string in Java

Split method in String class will break a string into tokens or array. By specify regular expression as delimiters, as the example below.Split a string into array, using a space as delimiter.

String str = "This is a test string";
String[] words = str.split(" ");
for (int i=0; i < words.length; i++)
  System.out.println(words[i]);
Output:
This
is
a
test
string

In some case that delimiter has a special meaning in a regular expression. You must add two backslashes (\\..) in front of the delimiter to make it as a character rather than the wildcard in a regular expression. Some examples of delimiter that has a special meaning are a dot(.), a star(*) , ‘|’ etc.

For a dot, must use delimiter as “\\.”

String str = "123.456.789.10.11";
String[] words = str2.split ("\\.");
for (int i=0; i < words.length; i++)
  System.out.println(words[i]);

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.

2 Comments

  1. Nico van der Heide September 26, 2007
  2. Edson Pessotti October 21, 2016

Leave a Reply