Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3541

Split a String in Java

$
0
0

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:

Iterable<String> result = Splitter.on(',')
  .trimResults()
  .omitEmptyStrings()
  .split("car,jeep,, scooter");
 
List<String> resultList = Lists.newArrayList(result);

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.


Viewing all articles
Browse latest Browse all 3541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>