The Wayback Machine - https://web.archive.org/web/20240905140138/https://www.geeksforgeeks.org/split-string-java-examples/
Open In App

Split() String method in Java with examples

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

Input String: 016-78967
Regular Expression: -
Output : {"016", "78967"}

Following are the two variants of the split() method in Java: 

1. Public String [] split ( String regex, int limit)

Parameters

  • regex – a delimiting regular expression
  • Limit – the resulting threshold

Returns 

An array of strings is computed by splitting the given string.

Exception Thrown

PatternSyntaxException – if the provided regular expression’s syntax is invalid.  

The limit parameter can have 3 values 

  • limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
  • limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
  • limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.

Here’s how it works:

Let the string that is to be split is – geekss@for@geekss

Regex  Limit  Result
@2{“geekss”, ”for@geekss”}
@5{“geekss”, ”for”, ”geekss”} 
@-2{“geekss”, ”for”, ”geekss”}
s    5{“geek”, ”“, “@for@geek”, “”, “”}
s    -2{“geek”, ” “, ” “, “@for@geek”, “”, “”}
s    0{“geek”, ””, ”@for@geek”}

Following are the Java example codes to demonstrate the working of split()
 
Example 1:

Java
// Java program to demonstrate working of split(regex,
// limit) with small limit.

public class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Custom input string
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("@", 2);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geekss
for@geekss

Example 2:  

Java
// Java program to demonstrate working of split(regex,
// limit) with high limit.
public class GFG {
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("@", 5);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geekss
for
geekss

Example 3:  

Java
// Java program to demonstrate working of split(regex,
// limit) with negative limit.
public class GFG {
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("@", -2);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geekss
for
geekss

Example 4:  

Java
// Java program to demonstrate working of split(regex,
// limit) with high limit.
public class GFG {
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("s", 5);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geek

@for@geek


Example 5:  

Java
// Java program to demonstrate working of split(regex,
// limit) with negative limit.
public class GFG {
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("s", -2);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geek

@for@geek


Example 6:  

Java
// Java program to demonstrate working of split(regex,
// limit) with 0 limit.

public class GFG {
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String[] arrOfStr = str.split("s", 0);

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
geek

@for@geek

2. public String[] split(String regex)

This variant of the split method takes a regular expression as a parameter and breaks the given string around matches of this regular expression regex. Here, by default limit is 0.

Parameters

regex – a delimiting regular expression

Returns

An array of strings is computed by splitting the given string.

Exception Thrown

PatternSyntaxException – if the provided regular expression’s syntax is invalid.  

Here are some working example codes:
 
Example 1:

Java
// Java program to demonstrate working of split()
public class GFG {
    public static void main(String args[])
    {
        String str
            = "GeeksforGeeks:A Computer Science Portal";
        String[] arrOfStr = str.split(":");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
GeeksforGeeks
A Computer Science Portal

Example 2:

Java
// Java program to demonstrate working of split()
public class GFG {
    public static void main(String args[])
    {
        String str = "GeeksforGeeksforStudents";
        String[] arrOfStr = str.split("for");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
Geeks
Geeks
Students

It can be seen in the above example that the pattern/regular expression “for” is applied twice (because “for” is present two times in the string to be split)

Example 3:  

Java
// Java program to demonstrate working of split()
public class GFG {
    public static void main(String args[])
    {
        String str = "Geeks for Geeks";
        String[] arrOfStr = str.split(" ");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
Geeks
for
Geeks

Example 4:

Java
// Java program to demonstrate working of split()
public class GFG {
    public static void main(String args[])
    {
        String str = "Geeks.for.Geeks";
        String[] arrOfStr
            = str.split("[.]"); // str.split("."); will give
                                // no output...

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
Geeks
for
Geeks

 Example 5: 

Java
// Java program to demonstrate working of split()
public class GFG {
    public static void main(String args[])
    {
        String str = "Geekssss";
        String[] arrOfStr = str.split("s");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
Geek

In the above example, trailing empty strings are not included in the resulting array arrOfStr.

Example 6:  

Java
// Java program to demonstrate working of split()

public class GFG {

    // Main driver method
    public static void main(String args[])
    {
        String str = "GeeksforforGeeksfor   ";
        String[] arrOfStr = str.split("for");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
Geeks

Geeks
   

In the above example, the trailing spaces (hence not empty string) become a string in the resulting array arrOfStr.
 
Example 7:  

Java
// Java program to demonstrate working of split()
// using regular expressions

public class GFG {

    public static void main(String args[])
    {
        String str = "word1, word2 word3@word4?word5.word6";
        String[] arrOfStr = str.split("[, ?.@]+");

        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output
word1
word2
word3
word4
word5
word6

In the above example, words are separated whenever either of the characters specified in the set is encountered.



Similar Reads

Pattern split(CharSequence) method in Java with Examples
split(CharSequence) method of a Pattern class used to splits the given char sequence passed as parameter to method around matches of this pattern.This method can split charSequence into an array of String's, using the regular expression used to compile the pattern as a delimiter.so we can say that the method returns the array of strings computed by
2 min read
Pattern split(CharSequence,int) method in Java with Examples
split(CharSequence, int) method of a Pattern class used to splits the given char sequence passed as parameter to method around matches of this pattern.The array returned contains each substring of the input sequence created by this method. The substrings in the array are in the order in which they occur in the input. If this pattern does not match
3 min read
How to split a string in C/C++, Python and Java?
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delimiters.// and returns next token. It needs to be ca
7 min read
StringJoiner Class vs String.join() Method to Join String in Java with Examples
Prior to Java 8 when we need to concatenate a group of strings we need to write that code manually in addition to this we needed to repeatedly use delimiter and sometimes it leads to several mistakes but after Java 8 we can concatenate the strings using StringJoiner class and String.join() method then we can easily achieve our goal. Example: Withou
6 min read
Difference Between StringTokenizer and Split Method in Java
Legacy classes and interfaces are the classes and interfaces that formed the Collection Framework in the earlier versions of Java and how now been restructured or re-engineered. Splitting of String is basically breaking the string around matches of the given regular expression. Strings can be split in many ways in java but the 2 most common ways ar
3 min read
Split a List into Two Halves in Java
Here we are given a list and the task is to split it into two news lists as one can better perceive from the below illustration as follows: Illustration: Input : list = {1, 2, 3, 4, 5, 6} Output : first = {1, 2, 3}, second = {4, 5, 6} Input : list = {1, 2, 3, 4, 5} Output : first = {1, 2}, second = {3, 4, 5} Methods: Using loops(Naive Approach)Usin
6 min read
String matches() Method in Java with Examples
Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same. Variants of String match
4 min read
Java String equalsIgnoreCase() Method with Examples
In Java, equalsIgnoreCase() method of the String class compares two strings irrespective of the case (lower or upper) of the string. This method returns a boolean value, true if the argument is not null and represents an equivalent String ignoring case, else false. Syntax of equalsIgnoreCase()str2.equalsIgnoreCase(str1);Parametersstr1: A string tha
2 min read
Java String format() Method With Examples
In Java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax of String format() There are two types of string format() methods mentioned below: public static String
3 min read
Java String subSequence() method with Examples
The Java.lang.String.subSequence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty
2 min read
String toString() Method in java with Examples
String toString() is the built-in method of java.lang which return itself a string. So here no actual conversion is performed. Since toString() method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly. Syntax : public String toString() Parameter: The method does no
1 min read
Matcher quoteReplacement(String) method in Java with Examples
The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods. Syntax: public static String quoteReplacement(String string)
2 min read
Matcher start(String) method in Java with Examples
The start(String string) method of Matcher Class is used to get the start index of the match result already done, from the specified string. Syntax: public int start(String string) Parameters: This method takes a parameter string which is the String from which the start index of the matched pattern is required. Return Value: This method returns the
2 min read
Matcher group(String) method in Java with Examples
The group(String string) method of Matcher Class is used to get the group of the match result already done, from the specified string. Syntax: public String group(String string) Parameters: This method takes a parameter string which is the String from which the group index of the matched pattern is required. Return Value: This method returns the gr
2 min read
Matcher replaceAll(String) method in Java with Examples
The replaceAll(String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public String replaceAll(String stringToBeReplaced) Parameters: This method takes a parameter stringToBeReplaced which is the String to be replaced in the ma
2 min read
Matcher replaceFirst(String) Method in Java with Examples
The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched pattern in the matcher string. Syntax: public String replaceFirst(String stringToBeReplaced) Parameters: The string to be replaced that is the String to be replaced in the matcher. Return Type
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters: This method takes two parameters: builde
3 min read
Matcher appendReplacement(StringBuffer, String) method in Java with Examples
The appendReplacement(StringBuffer, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuffer buffer, String stringToBeReplaced) Parameters: This method takes two parameters: buffer: w
3 min read
ZoneOffset of(String) method in Java with Examples
The of(String) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offsetId passed as the parameter. This method takes the offsetId as parameter in the form of String and converts it into the ZoneOffset. The ID of the returned offset will be normalized to one of the formats described by getId(). The
2 min read
PrintWriter println(String) method in Java with Examples
The println(String) method of PrintWriter Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Syntax: public void println(String string) Parameters: This method accepts a mandatory parameter string which is the String to be printed in the Stream. Return Value: This method d
2 min read
PrintWriter print(String) method in Java with Examples
The print(String) method of PrintWriter Class in Java is used to print the specified String value on the stream. This String value is taken as a parameter. Syntax: public void print(String StringValue) Parameters: This method accepts a mandatory parameter StringValue which is the String value to be written on the stream. Return Value: This method d
2 min read
PrintWriter write(String, int, int) method in Java with Examples
The write(String, int, int) method of PrintWriter Class in Java is used to write a specified portion of the specified String on the stream. This String is taken as a parameter. The starting index and length of String to be written are also taken as parameters. Syntax: public void write(String string, int startingIndex, int lengthOfstring) Parameter
2 min read
PrintWriter write(String) method in Java with Examples
The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Syntax: public void write(String string) Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any valu
2 min read
PrintWriter printf(Locale, String, Object) method in Java with Examples
The printf(Locale, String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter printf(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintWriter printf(String, Object) method in Java with Examples
The printf(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter printf(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintWriter format(String, Object) method in Java with Examples
The format(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintStream printf(String, Object) method in Java with Examples
The printf(String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream printf(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintWriter format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream printf(Locale, String, Object) method in Java with Examples
The printf(Locale, String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream printf(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read