Split a String in Java

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. 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(","))
  .map(String::trim)
  .toArray(String[]::new);

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

Related posts:

Java Program to Implement Aho-Corasick Algorithm for String Matching
Java Program to Implement Segment Tree
Guide to Spring @Autowired
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Spring Boot - Cloud Configuration Client
Java Program to Implement VList
Life Cycle of a Thread in Java
Custom Exception trong Java
Java Program to Use Dynamic Programming to Solve Approximate String Matching
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Implement LinkedTransferQueue API
Logout in an OAuth Secured Application
Spring WebClient and OAuth2 Support
HashSet trong Java hoạt động như thế nào?
Convert XML to JSON Using Jackson
Introduction to the Java NIO2 File API
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Introduction to Spring Cloud CLI
Converting a List to String in Java
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java – Write an InputStream to a File
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Java Program to Implement Depth-limited Search
Spring Security OAuth Login with WebFlux
Python String isidentifier()
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Python String isupper()
Sắp xếp trong Java 8
Java Program to Implement LinkedHashMap API
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
HashSet trong java