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:

Python String zfill()
Java Program to Find Minimum Element in an Array using Linear Search
Java Program to Implement Cubic convergence 1/pi Algorithm
Java Scanner hasNext() vs. hasNextLine()
Jackson – Decide What Fields Get Serialized/Deserialized
Integer Constant Pool trong Java
Java Program to Implement Dijkstra’s Algorithm using Set
How to Find an Element in a List with Java
Converting Between an Array and a Set in Java
Python String isprintable()
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Hướng dẫn Java Design Pattern – Template Method
Java Program to Implement Hash Tables Chaining with List Heads
Cơ chế Upcasting và Downcasting trong java
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Từ khóa this và super trong Java
Java Program to Implement the Vigenere Cypher
Cachable Static Assets with Spring MVC
Java Program to Implement Pairing Heap
Quick Guide to the Java StringTokenizer
Hướng dẫn sử dụng Java Generics
Guide to PriorityBlockingQueue in Java
Spring Boot - Tomcat Deployment
Handling Errors in Spring WebFlux
Spring MVC Custom Validation
Java Program to Implement Stack API
Write/Read cookies using HTTP and Read a file from the internet
Ép kiểu trong Java (Type casting)
Java Program to Perform Searching Based on Locality of Reference
MyBatis with Spring
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Java Program to Perform Partial Key Search in a K-D Tree