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 Algorithms, Competitive Programming, JavaScript, System Design, Machine 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 problems, interview experiences, and interview bundle for placement preparations.
Recommended problems -
Nevertheless, you may consider our paid courses to give your career an edge over others!