Java String split

Filed Under: Java

Java String split() method is used to split the string into a string array based on the provided regular expression.

Java String split

Sometimes we have to split String in Java, for example splitting data of CSV file to get all the different values.

String class provides two useful methods to split a string in java.

  1. public String[] split(String regex): This java string split method is used to split the string based on the given regular expression string. The whole string is split and returned in the form of a string array. This method was introduced in Java 1.4. Notice that the trailing empty strings are not included in the returned string array. Let’s look at a simple java string split example to understand this.
    
    String s = "abcaada";
    System.out.println(Arrays.toString(s.split("a")));
    

    Above code will produce output as [, bc, , d]. Notice that the last empty string is excluded from the returned string array.

  2. public String[] split(String regex, int limit): This java string split method is used when we want the string to be split into a limited number of strings. For example, let’s say we have a String variable that contains name and address with comma as a delimiter. Now, the address can have commas in them, so we can use this method. A short example of this string split is given below.
    
    String s = "Pankaj,New York,USA";
    String[] data = s.split(",", 2);
    System.out.println("Name = "+data[0]); //Pankaj
    System.out.println("Address = "+data[1]); //New York,USA
    
  3. Note that the first method above actually utilizes the second method by passing limit as 0.

    
    public String[] split(String regex) {
        return split(regex, 0);
    }
    

Java String split important points

Some important points about java String split method are:

  • The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string.
  • If the regex doesn’t match any part of the input string then the resulting array has just one element, namely this string.
  • The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n – 1 time, the array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter.

    If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

    If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Java String split example

Here is an example of java String split method.


package com.journaldev.util;

import java.util.Arrays;

public class JavaStringSplit {

	/**
	 * Java String split example
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String line = "I am a java developer";

		String[] words = line.split(" ");

		String[] twoWords = line.split(" ", 2);

		System.out.println("String split with delimiter: " + Arrays.toString(words));

		System.out.println("String split into two: " + Arrays.toString(twoWords));

		// split string delimited with special characters
		String wordsWithNumbers = "I|am|a|java|developer";

		String[] numbers = wordsWithNumbers.split("\\|");

		System.out.println("String split with special character: " + Arrays.toString(numbers));

	}
}

Below image shows the output produced by the above String split example program.

java string split

We can use a backslash to use java regular expression special characters as normal characters like I have used pipe (|) special character in the above program.

That’s all for a quick roundup on java string split example.

Reference: API Doc

Comments

  1. jem says:

    Hi! I want to input a integer then my output will be all separated by a comma, Can you help with this problem?

  2. Zoom says:

    Hi,

    I would like to print only the string which meets a criteria, in this case a special character (-). Please help

    String line = “I am a ja-va developer”;

    Expected: ja-va

    1. Dushyant Sheoran says:

      Hi Zoom,
      I suppose if there are multiple instances then you need all of them.
      One way is to create a similar array by splitting and then keeping the instances that you need.
      Or you can simply search for the special character instances and print the element around it by splitting based on the condition ,it seems that it space character or “.”
      Thanks

  3. S.GokulaGokhila says:

    I am doing Mphil.In My Research Work,I want split Comma only four then Remaining text needed for me then Perform other remaining steps………

    1. Dushyant Sheoran says:

      Hi S.GokulaGokhila,
      You can split the string into five such segments by using something like :: stringName.split(“*”, 4);
      Where * is the basis of the split.
      Thanks

  4. Prashanth R says:

    Nice Articles.. Good work..

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages