How to split a String in Java?

  1. Accepted Answer - Using String.split() method
  2. Accepted Answer - Split a string by space or whitespace characters
  3. Accepted Answer - String.split() with a limit
  4. Accepted Answer - String.split() with Multiple Delimiters

Accepted Answer - Using String.split() method

Perhaps the easiest way to split simple strings in Java is to use the String.split() method. The argument to this method is a regex that will be used to break a String into parts. The output is an array generated by splitting this string around matches of the given regular expression.

For example, to split a String separate by dashes -, we can do the following:

String phone = "403-999-4999";

String [] phoneParts = phone.split("-"); // split by -

String areaCode = phoneParts[0]; // 403

for (String s : phoneParts) {
    System.out.println(s);
}

// Prints
// 403
// 999
// 4999

Note that String.split() method uses regular expressions so if you’re using special characters such as backslash \, dollar sign $, period ., you must escape them using \\

E.g. to split a string by a special character such as period ., you can:

  1. escape them using double backslashes \\.
  2. use character class [.] (recommended in all cases)
  3. use Pattern.quote(".")
String str = "java.com"; // split by .
String [] arr = str.split("\\.");

for (String s: arr) {
    System.out.println(s);
}

//Prints
//java
//com

Accepted Answer - Split a string by space or whitespace characters

To split a string by space, use \\s+. It will split the string by single or multiple whitespace characters such as space, tab, etc.

String str = "one_space   multiple_spaces    tab";
String [] arr = str.split("\\s+");

// arr[0] = one_space
// arr[1] = multiple_spaces
// arr[2] = tab

Accepted Answer - String.split() with a limit

String.split() also supports a second argument to limit the numbers of times the regex pattern is applied and the string is split before stopping. The limit argument is applied n-1 times. So if you pass 2, it will be applied once.

For example, to get the first match only

String str = "blog.unlaunch.io";
String [] arr = str.split("\\.", 2);

System.out.println(arr.length); // 2

for (String s: arr) {
    System.out.println(s);
}

// Prints
// blog
// unlaunch.io

Accepted Answer - String.split() with Multiple Delimiters

If the String contain multiple delimiters, pass them all to the split() method. Suppose, we want to split a string by either a period . or ;, we can do this using:

String str = "123.code;$abc";
String [] arr = str.split("[.;]");

// arr[0] = 123
// arr[1] = code
// arr[2] = $abc

Speak Your Mind