If you’re working with Spring, check out "REST With Spring":

>> CHECK OUT THE COURSE

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 = "192.168.1.178".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(',')
  .trimResults()
  .omitEmptyStrings()
  .splitToList("car,jeep,, scooter");

5. 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.

The new Certification Class of "REST With Spring" is finally out:

>> CHECK OUT THE COURSE