I just announced the new Spring 5 modules in 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.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
Slava Semushin
Guest

It’s a bit odd to create a list only to be able to convert it to array later (Arrays.asList(“car”, “jeep”, “scooter”).toArray()). Why not just create an array (new String[]{“car”, “jeep”, “scooter”})?

Grzegorz Piwowarek
Guest

Actually, It would make even more sense to use Assertj. We will update it.

EDIT:
Actually, we ended up removing the assertions from the article but still introduced Assertj to the codebase