How to split a string in Java

In this post we will provide some examples on how to split a string in Java

How to split a string in Java

If we have a string 01234-5678 and we want to split it, so we have two strings of 01234 and 5678. This can be achieved in two ways.

Example 1: Using standard Java

You can split the string using the split() method. You will need to pass it a regex on how to split the string.

Running the above code produces the following output:

Example 2: Using Guava

For this example you will need to add the following dependency:

You can split the string using the on() method passing in your regex. It also has other useful methods you can chain such as trimResults to remove whitespace, limit to reduce the number of results returned and omitEmptyStrings which will remove empty results from the returned list.

Running the above code produces the following output

As you can see the Splitter class has some very useful helper methods when splitting a string.

 

Similar posts:

  1. Java String basics
  2. How to sort an Array in Java
  3. Convert a string to list split by new line
  4. CountDownLatch in Java

References:

  1. Java 8 String API
  2. Splitter API documentation

Leave a Reply