Home » Core Java » lang » String » Java String split Example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Java String split Example

In this Java String split example we are going to see how to split a String in Java into smaller sub strings. It is extremely common to want to split a String into parts. These parts are separated by a specific delimiter. And in order to avoid parsing the String yourself, Java offers split API method.

1. Using split

It is very easy to split a String in Java using split. It works like this : you give it a delimiter as argument, and it returns the sub parts of the String that are separated with the specified delimiter into an String array. The delimiter can be very simple, like a single character, or very complex like a regular expression. In fact this is the complete signature of the method : public String[] split(String regex)

Ok let’s see how you can use it:

StringSplitExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.javacodegeeks.core.string;
import java.util.Arrays;
 
public class StringSplitExample {
 
    public static void main(String[] args) {
 
        String str = "abdc:psdv:sdvosdv:dfpbkdd";
 
        // split the array using ':' as a delimiter
        String[] parts = str.split(":");
 
        System.out.println("Using : as a delimiter "+Arrays.toString(parts));
 
        // split the array using 'd' as a delimiter
        parts = str.split("d");
        System.out.println(Arrays.toString(parts));
 
        String str2 = "This is a string to tokenize";
 
        // tokenize the string into words simply by splitting with " "
        parts = str2.split(" ");
        System.out.println(Arrays.toString(parts));
    }
}

This will be the output:

[abdc, psdv, sdvosdv, dfpbkdd]
[ab, c:ps, v:s, vos, v:, fpbk]
[This, is, a, string, to, tokenize

Some important things to note:

  • The array, returned by split, contains all sub strings of the original String that end with the specified delimiter.
  • The sub strings in the array appear in the same order as in the original String.
  • If none of the characters match the delimiter the array will have only one String, the original one.

2. Using split with limit

You can also use public String[] split(String regex, int limit), to set a limit on how many times you want the string to be split. Essentially, the String will be scanned sequentially from left to right, and spit the String as it normally would, but it will stop as soon as it performs limit splits.

Take a look at this example:

StringSplitExample.java

package com.javacodegeeks.core.string;
import java.util.Arrays;
 
public class StringSplitExample {
 
    public static void main(String[] args) {
 
        String str = "abdc:psdv:sdvosdv:dfpbkdd";
 
        String[] part0Limits = str.split(":",0);
 
        System.out.println("Using : as a delimiter with limit 0 " +Arrays.toString(part0Limits));
        
        String[] part1Limits = str.split(":",2);
        System.out.println("Using : as a delimiter with limit 1 " +Arrays.toString(part1Limits));
        
        String[] part5Limits = str.split(":",5);
        System.out.println("Using : as a delimiter with limit 5 " +Arrays.toString(part5Limits));
        
        String[] partNegativeLimits = str.split(":",-2);
        System.out.println("Using : as a delimiter with negative limit " +Arrays.toString(partNegativeLimits));
        
	}
}

This will be the output:

Using : as a delimiter with limit 0 [abdc, psdv, sdvosdv, dfpbkdd]
Using : as a delimiter with limit 1 [abdc, psdv:sdvosdv:dfpbkdd]
Using : as a delimiter with limit 5 [abdc, psdv, sdvosdv, dfpbkdd]
Using : as a delimiter with negative limit [abdc, psdv, sdvosdv, dfpbkdd]
  • The array, returned by split(), contains all substrings of the original String that end with the specified delimiter(:) If you specified the limit is 2, it will return only the two substrings.
  • If the limit is negative -2, then the method returns the substring with no limit.
  • If the limit is 0, then the method returns all substring excluding the trailing empty string.

3. Using split with regular expressions

Some times it is very convenient to use a regular expression instead of a delimiter to split a String. For example, you may want to split a String using any number as a delimiter, and not just a constant character.

Let’s see how you can do that:

StringSplitExample.java

package com.javacodegeeks.core.string;

import java.util.Arrays;

public class StringSplitExample {

	public static void main(String[] args) {

		String str = "abdc124psdv456sdvos456dv568dfpbk0dd";

		// split the array using a single digit, e.g 1,2,3...
		String[] parts = str.split("[0-9]");
		System.out.println(Arrays.toString(parts));

		// split the array using a whole number, e.g 12,346,756
		parts = str.split("[0-9]+");
		System.out.println(Arrays.toString(parts));

		//split the string using series of operators
		System.out.println("Split string using operators :");
		String input = "test,java,code-geek@java8?split.example";
		String[] strOutput = input.split("[,-?.@]+");
		for (String s : strOutput)
			System.out.println(s);

		// split the string using ^
		System.out.println("Split string using ^ :");
		String input2 = "Java^CodeGeeks";
		String strOutput2[] = input2.split("\\^");
		for (String s : strOutput2)
			System.out.println(s);

	}
}

This will be the output:

[abdc, , , psdv, , , sdvos, , , dv, , , dfpbk, dd]
[abdc, psdv, sdvos, dv, dfpbk, dd]
Split string using operators :
test
java
code
geek
java
split
example
Split string using ^ :
Java
CodeGeeks

The array, returned by split(), contains all substrings, which is split using expressions using operators or numbers.

4. Download the source code

This was an example on Java String split.

Download
You can download the source code of this example here : Java String split Example

Last updated on Mar. 23rd, 2020

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of