0% found this document useful (0 votes)
39 views14 pages

Java Split Method with Negative Limit

The document discusses the split() method in Java which is used to split a string into an array of substrings based on a regular expression or delimiter. It provides examples of using split() with different parameters like limit, regex patterns and trailing strings.

Uploaded by

praveen kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views14 pages

Java Split Method with Negative Limit

The document discusses the split() method in Java which is used to split a string into an array of substrings based on a regular expression or delimiter. It provides examples of using split() with different parameters like limit, regex patterns and trailing strings.

Uploaded by

praveen kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

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 = [Link]("@", 2);

        for (String a : arrOfStr)

            [Link](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 = [Link]("@", 5);

        for (String a : arrOfStr)

            [Link](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 = [Link]("@", -2);

        for (String a : arrOfStr)

            [Link](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 = [Link]("s", 5);


 

        for (String a : arrOfStr)

            [Link](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 = [Link]("s", -2);


 

        for (String a : arrOfStr)

            [Link](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 = [Link]("s", 0);

        for (String a : arrOfStr)

            [Link](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 = [Link](":");

        for (String a : arrOfStr)

            [Link](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 = [Link]("for");

        for (String a : arrOfStr)

            [Link](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 = [Link](" ");

 
        for (String a : arrOfStr)

            [Link](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 = "[Link]";

        String[] arrOfStr

            = [Link]("[.]"); // [Link]("."); will give

                                // no output...

        for (String a : arrOfStr)


            [Link](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 = [Link]("s");

        for (String a : arrOfStr)

            [Link](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 = [Link]("for");

        for (String a : arrOfStr)

            [Link](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 = [Link]("[, ?.@]+");

        for (String a : arrOfStr)

            [Link](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.
This article is contributed by Vaibhav Bajpai. If you like GeeksforGeeks and would
like to contribute, you can also write an article using [Link]. See your
article appearing on the GeeksforGeeks main page and help other Geeks. Please write
comments if you find anything incorrect or if you want to share more information about
the topic discussed above

Common questions

Powered by AI

Using special characters like '.' in Java's split() method requires careful handling since '.' is a special regex character representing any character. To ensure the split is correctly interpreted as a literal period, you must escape it using double backslashes as in `"\."` or bracket notation `[.]` . Without escaping, the split will fail to produce the correct output because it incorrectly interprets the '.' as a wildcard .

The default behavior of the `split(String regex)` method in Java is equivalent to calling `split(regex, 0)`, where the string is split around matches of the given regular expression and trailing empty strings in the resulting array are discarded . This is because when no limit is specified, it defaults to zero, affecting how trailing elements are treated .

Using the `[.]` pattern is necessary over using `.` directly when you need to split strings by literal periods. In regular expressions, `.` is a metacharacter representing any character. Using `[.]` within brackets treats it as a literal dot, allowing correct splitting. For instance, `str.split("[.]")` on "Geeks.for.Geeks" correctly separates into `{“Geeks”, “for”, “Geeks”}`, while using direct `.` would incorrectly treat it as any character, not effectively splitting on literal periods .

In Java's `split()` method, trailing empty strings are handled differently depending on the `limit` parameter. If the limit is less than zero, all results, including trailing empty strings, are included in the output array . If the limit is zero, trailing empty strings are discarded from the resulting array . If the limit is positive, the potential trailing section beyond the last split is included only up to the number of allowed elements specified by the limit .

When the `split()` method's limit is greater than zero, the pattern is applied at most limit-1 times. This means the resulting array's length will not exceed the specified limit, and the last element of the array will contain the remainder of the string beyond the last matched pattern . For example, using the string "geekss@for@geekss" and applying `split("@", 2)`, the result would be `{“geekss”, ”for@geekss”}` where the limit stops further splitting after the first occurrence .

When the limit parameter in the Java `split()` method is set to a negative value, the pattern is applied as many times as possible, and the resulting array can be of any size without removing trailing empty strings . This is because the method does not attempt to discard any part of the string once the limit is negative. In contrast, when the limit is set to zero, the pattern is also applied as many times as possible, but trailing empty strings in the resulting array are discarded .

Using different delimiters significantly impacts the results of splitting the string "GeeksforGeeksforStudents". For example, using `split("for")` breaks it into `{“Geeks”, “Geeks”, “Students”}` since "for" appears twice and is used as the delimiter . This demonstrates that the choice of delimiter affects both the number and nature of resultant substrings. If a delimiter exists multiple times within the string, it results in breaking points at each occurrence, while seldom occurring or inappropriate delimiters could lead to an unchanged string or minimal splitting . This illustrates the importance of selecting appropriate delimiters based on the expected structure of the input data .

A `PatternSyntaxException` can occur when using the `split()` method if the provided regular expression is not correctly formatted, rendering it invalid . To avoid this, make sure the regex follows correct syntax rules, particularly regarding escape sequences for special characters, proper use of brackets, and matching parentheses or brackets .

The `split()` method in Java can help manage mismatched regex characters by allowing the developer to specify patterns that correctly interpret or ignore these characters. For instance, to split based on a literal dot, a regular expression like `[.]` should be used. This prevents the default behavior where a dot would match any character, thus avoiding unexpected splitting outcomes . Handling mismatched characters in this way ensures predictable splitting behavior, essential in applications that process user-generated strings or external data with potential syntax conflicts .

Using the `split()` method with the regex `[,. ?@]+` would be beneficial in scenarios where a string contains multiple delimiters that need to be considered simultaneously for splitting. This regex matches any number of commas, spaces, question marks, at symbols, or periods. If used on the string "word1, word2 word3@word4?word5.word6", it effectively separates into `{“word1”, “word2”, “word3”, “word4”, “word5”, “word6”}` by splitting at any group of these delimiters . This approach is useful for parsing text where delimiters change dynamically, such as in parsing user input or documents with inconsistent formatting .

You might also like