1. Introduction

Splitting Strings is a very frequent operation; this quick tutorial is focused on some of the API we can use to do this simply in Java.

2. String.split()

Let’s start with the core library – the String class itself offers a split() method – which is very convenient and sufficient for most scenarios. It simply splits the given String based on the delimiter, returning an array of Strings.

Let us look at some examples. We’ll start with splitting by a comma:

String[] splitted = "peter,james,thomas".split(",");

Let’s split by a whitespace:

String[] splitted = "car jeep scooter".split(" ");

Let’s also split by a dot:

String[] splitted = "".split("\\.")

Let’s now split by multiple characters – a comma, space, and hyphen through regex:

String[] splitted = "b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*"));

3. StringUtils.split()

Apache’s common lang package provides a StringUtils class – which contains a null-safe split() method, that splits using whitespace as the default delimiter:

String[] splitted = StringUtils.split("car jeep scooter");

Furthermore, it ignores extra spaces:

String[] splitted = StringUtils.split("car   jeep  scooter");

4. Splitter.split()

Finally, there’s a nice Splitter fluent API in Guava as well:

List<String> resultList = Splitter.on(',')
  .splitToList("car,jeep,, scooter");

5. Split and Trim

Sometimes a given String contains some leading, trailing, or extra spaces around the delimiter. Let’s see how we can handle splitting the input and trimming the results in one go.

Let’s say we have this as an input:

String input = " car , jeep, scooter ";

To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex:

String[] splitted = input.trim().split("\\s*,\\s*");

Here, trim() method removes leading and trailing spaces in the input string, and the regex itself handles the extra spaces around delimiter.

We can achieve the same result by using Java 8 Stream features:

String[] splitted = Arrays.stream(input.split(","))

6. Splitting String Into Two Halves

We can split a string into two parts by getting its midpoint and using substring() to get the separated parts.

Here’s an example that splits a string in half:

String hello = "Baeldung";
int mid = hello.length() / 2;
String[] parts = { hello.substring(0, mid), hello.substring(mid) };

Here, we calculate the midpoint of the string value. Next, we use the substring() method to get the first and second parts of the string value by specifying the ranges.

7. Conclusion

String.split() is generally enough. However, for more complex cases we can utilize Apache’s commons-lang based StringUtils class, or the clean and flexible Guava APIs.

And, as always, the code for the article is available over on GitHub.