Table of contents
1.
Introduction
2.
What is String Split() in Java?
2.1.
Parameters of String split()
2.2.
Syntax of String split()
2.2.1.
If limit is not given
2.2.2.
If limit is given
2.3.
Return value of String split()
3.
Implementation of string split() without limit
4.
Implementation of string split() with limit
5.
Types of the split() Methods in Java
5.1.
1. split(String regex)
5.2.
2. split(String regex, int limit)
6.
Advantages of Split() in Java
7.
Frequently Asked Questions
7.1.
What are some of the predefined methods in the Java string class?
7.2.
What if the provided regex is not present in the string?
7.3.
What are some of the use cases of string split() in real life?
8.
Conclusion
Last Updated: Sep 8, 2024

String split() in Java

Author Md Yawar
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java is one of the most widely used programming languages in the world. It has predefined data structures used to store data. For example, ArrayList, Strings, etc. A string in Java is defined as an object that represents a sequence of char values. The Java string class provides many predefined methods that allow us to perform various operations on strings. One such method is split(), which is used to split the string. In this blog, we will discuss string split ().

string.split()

What is String Split() in Java?

The `String.split()` method in Java is used to divide a given string around matches of a specified regular expression. After executing the split operation, the method returns an array containing the substrings. This is particularly useful for extracting parts of a string based on specific patterns or delimiters, such as spaces, commas, or custom separators.

For example, splitting a comma-separated string into an array of values allows for easy access to individual elements. The method can be configured to limit the number of substrings returned by providing a second argument to the method. If the pattern is not found in the string, the method will return an array containing the original string as the only element.

Parameters of String split()

There are two parameters of string split():

String regex: It is the regular expression that we give. The string is divided at this regex.

Int limit: It gives us the number of the resulting substrings. It is optional, and if not given, string split() will return all the possible substrings of the string divided by the regex. If the limit is 0, it will return all the possible resultant substring.

Syntax of String split()

The syntax of string split() is:

If limit is not given

string.split(string regex)

If limit is given

string.split(string regex, int limit)

Return value of String split()

After splitting the string around the given regex, it returns the array of strings that we get after splitting the string. The number of substrings is decided by the limit parameter. If no limit is given, it will return all the possible resultant substrings.

Implementation of string split() without limit

import java.io.*;

class Main {

  public static void main(String[] args) {

    // initializing the string
    String text = "Welcome to coding-ninjas";

    // split string from the given regex
    String[] result1 = text.split(" ");
    String[] result2 = text.split("-");

    //printing the result
    System.out.print("result1 = ");
    for (String str : result1) {
      System.out.print(str + ", ");
    }
    
    System.out.println();
    
    System.out.print("result2 = ");
    for (String str : result2) {
      System.out.print(str + ", ");
    }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

result1 = Welcome, to, coding-ninjas, 
result2 = Welcome to coding, ninjas, 

Implementation of string split() with limit

import java.io.*;

class Main {

  public static void main(String[] args) {

    // initializing the string
    String text = "Coding ninjas Coding Ninjas Studio provides a complete preparation guide for coding interviews";

    // split string from the given regex and providing the limit
    String[] result1 = text.split(" ", 5);
    String[] result2 = text.split(" ", 11);

    //printing the result
    System.out.print("result1 = ");
    for (String str : result1) {
      System.out.print(str + ", ");
    }
    
    System.out.println();
    
    System.out.print("result2 = ");
    for (String str : result2) {
      System.out.print(str + ", ");
    }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

result1 = Coding, ninjas, Coding Ninjas Studio, provides, a complete preparation guide for coding interviews, 
result2 = Coding, ninjas, Coding Ninjas Studio, provides, a, complete, preparation, guide, for, coding, interviews, 

Types of the split() Methods in Java

In Java, the String.split() method has two primary forms, which provide flexibility in handling how strings are split based on delimiters or patterns. Let's discuss these two types in detail with examples:

1. split(String regex)

This method splits the string around matches of the given regular expression regex. If the regex does not match any part of the string, the original string is returned as the only item in the array.

Example:

String sentence = "one,two,three";
String[] words = sentence.split(",");
for(String word : words) {    
System.out.println(word);
}
You can also try this code with Online Java Compiler
Run Code

Output:

one
two
three

2. split(String regex, int limit)

This version of split() allows you to control the number of substrings in the resulting array with the limit parameter. If the limit is positive, the pattern will be applied at most limit - 1 times and the array can have at most limit elements. If the limit is negative, the pattern will be applied as many times as possible, and the array can have any length. If the limit is zero, the pattern will be applied as many times as possible, and trailing empty strings will be discarded.

Example:

String sentence = "one,two,three";
String[] words = sentence.split(",", 2);
for(String word : words) {    
System.out.println(word);
}
You can also try this code with Online Java Compiler
Run Code

Output:

one
two,three

In this example, the limit is set to 2, which means the array is limited to two elements, where the first split occurs at the first comma, and the rest of the string after the first comma remains intact as the second element of the array.

Advantages of Split() in Java

 

1. String Tokenization: The split() method allows you to easily tokenize a string into an array of substrings based on a specified delimiter. This is particularly useful when working with structured data formats like CSV (Comma-Separated Values) or TSV (Tab-Separated Values), where you need to extract individual elements from a string.

2. Flexible Delimiter: The split() method accepts a regular expression as the delimiter, providing flexibility in defining the splitting pattern. You can use simple characters, such as commas or spaces, or more complex regular expressions to handle various delimiter patterns.

3. Customizable Splitting Behavior: By using the overloaded version of split() with the limit parameter, you can control the number of splits performed. This is handy when you want to split a string only a certain number of times or include trailing empty strings in the resulting array.

4. Efficient String Processing: The split() method is optimized for performance and provides an efficient way to split strings. It internally uses a compiled regular expression to split the string, which is faster compared to manually iterating over the string and splitting it character by character.

5. Integration with Regular Expressions: Since the split() method uses regular expressions as the delimiter, you can leverage the power of regex patterns to split strings based on complex conditions. This allows you to handle scenarios where the delimiter is not a simple character but follows a specific pattern.

6. Concise and Readable Code: Using the split() method makes your code more concise and readable compared to manually splitting the string using loops and conditional statements. It encapsulates the splitting logic in a single method call, making the code more expressive and easier to understand.

7. Compatibility with Java API: The split() method is part of the Java standard library and is available in all Java versions. It integrates seamlessly with other string manipulation methods and can be used in conjunction with various Java APIs and frameworks, ensuring wide compatibility and portability.

Frequently Asked Questions

What are some of the predefined methods in the Java string class?

CharAt(), startsWith(), equals(), trim() are some of the predefined methods in Java string class.

What if the provided regex is not present in the string?

The whole string is returned as it is if the regex is not present in the string.

What are some of the use cases of string split() in real life?

String split can be used to separate the parts of an HTTP request header, separate parts of a name, get the phone numbers, etc.

Conclusion

This blog talked about the string split() method. We also implemented it in Java. You must be eager to learn more about the Java string class. Refer to our Guided Path to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.
 

Recommended problems -

Nevertheless, you may consider our paid courses to give your career an edge over others!

Live masterclass