Java/J2EE and SOA (346 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (17 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (343 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Split Method in Java: How to Split a String in Java?

Last updated on Nov 28,2019 33.1K Views

8 / 12 Blog from Java Strings

Splitting strings is a very frequent operation performed when coding. There are many ways to split a string in Java but the most common way is using the String split() method. This article is focused on how to split strings using the split method in Java.

Listed below are the topics covered in this article:

Split Method in Java

The String class in Java offers a split() method that can be used to split a string into an array of String objects based on delimiters that match a regular expression. For instance, given the following string:

String s = "Welcome, To, Edureka!";

You can split the string into sub-strings using the following piece of code:

String[] result = s.split(",");

More accurately, that expression will break the string into sub-strings wherever the sub-strings are separated by delimiter characters. In the above example, the input string ‘Welcome, To, Edureka’, is split into three string objects, namely:

Welcome
To
Edureka!

There are two variants of a split() method in Java. Let’s discuss each of them.

Using a split() method without limit parameter

This variant of the split() method accepts a regular expression as a parameter and breaks the given string based on the regular expression regex. Here the default limit is 0. Listed below are the syntax, parameter, return value, exceptions thrown and a lot of example programs demonstrating the concept.

Syntax: public String[] split(String regex)

Parameter: regex (a delimiting regular expression)

Return Value: an array of String objects

Exception: PatternSyntaxException, if the provided regular expression’s syntax is invalid

Example1: Calling a split() method on String Object – Splitting by a comma

package MyPackage;

public class Method1 { 
    public static void main(String args[]) 
    { 
    	String str = "We're,Ridiculously,Committed!"; 
        String[] arrOfStr = str.split(","); 
         System.out.println("Number of substrings: "+arrOfStr.length);
        
         for(int i=0; i< arrOfStr.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr[i]);
         }

    } 
}  

Output

Number of substrings: 3
str[0] : We're
str[1] : Ridiculously
str[2] : Committed!

Example2: Calling a split() method on String Object – Splitting by a whitespace

package MyPackage;

public class Method2 { 
    public static void main(String args[]) 
    { 
    	String str = "We're Ridiculously Committed! Welcome"; 
        String[] arrOfStr = str.split(" "); 
         System.out.println("Number of substrings: "+arrOfStr.length);
        
         for(int i=0; i< arrOfStr.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr[i]);
         }

    } 
}  

Output

Number of substrings: 4
str[0] : We're
str[1] : Ridiculously
str[2] : Committed!
str[3] : Welcome

Example3: Calling a split() method on String Object – Splitting by a dot

package MyPackage;

public class Method3 { 
    public static void main(String args[]) 
    { 
    	String str = "We're.Ridiculously.Committed.Welcome"; 
        String[] arrOfStr = str.split("."); 
         System.out.println("Number of substrings: "+arrOfStr.length);
        
         for(int i=0; i< arrOfStr.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr[i]);
         }

    } 
}  

Output

Number of substrings: 4
str[0] : We're
str[1] : Ridiculously
str[2] : Committed
str[3] : Welcome

Example4: Calling a split() method on String Object – Splitting by using a letter

package MyPackage;

public class Method4 { 
    public static void main(String args[]) 
    { 
    	String str = "We're Ridiculously Committed! Welcome"; 
        String[] arrOfStr = str.split("W"); 
         System.out.println("Number of substrings: "+arrOfStr.length);
        
         for(int i=0; i< arrOfStr.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr[i]);
         }

    } 
}  

Output

Number of substrings: 3
str[0] : 
str[1] : e're Ridiculously Committed! 
str[2] : elcome

Example5: Calling a split() method on String Object – Splitting by multiple delimiters

package MyPackage;

public class Method5 { 
    public static void main(String args[]) 
    { 
    	String str = "We're, Ridiculously Committed! Welcome to Eduerka.Hello"; 
        String[] arrOfStr = str.split("[, .!]+"); 
         System.out.println("Number of substrings: "+arrOfStr.length);
        
         for(int i=0; i< arrOfStr.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr[i]);
         }

    } 
}  

Output

Number of substrings: 7
str[0] : We're
str[1] : Ridiculously
str[2] : Committed
str[3] : Welcome
str[4] : to
str[5] : Eduerka
str[6] : Hello

Well, it’s simple enough, right? But what if you require only the first ‘n’ elements after the split operation but want the rest of the string to remain as it is? For that, we have another variant of the split() method.

Using a split() method with the limit parameter

This variant of the split() method is used when we want the string to be split into a limited number of strings. The only difference between this variant of split() method and other one is that it limits the number of strings returned after split up. The limit can be given as an input parameter to the split() method. The limit parameter controls the number of times the pattern is applied and hence affects the length of the resulting array.

Listed below are the syntax, parameter, return value, exceptions thrown and a lot of example programs demonstrating the concept.

Syntax: public String[] split(String regex, int limit)

Parameter: 

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

The limit can have 3 values, which are:

  1. limit > 0: If the limit is positive, then the pattern will be applied at most limit-1 times. The resulting array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter.
  2. limit < 0: If the limit is positive, then the pattern will be applied as many times as possible and the resulting array can have any length.
  3. limit = 0: If the limit is equal to 0, the pattern will be applied as many times as possible, the resulting array can have any length but the trailing empty strings will be discarded.

Return Value: an array of String objects computed by splitting the given string according to limit parameter

Exception: PatternSyntaxException, if the provided regular expression’s syntax is invalid

Example: Calling a split() method on String Object with the limit parameter

package MyPackage;

public class SplitMethod { 
    public static void main(String args[]) 
    { 
    	String str = "468-567-7388";
        String[] arrOfStr1 = str.split("8",2); 
        System.out.println("Output when limit is +ve");
         System.out.println("Number of substrings: "+arrOfStr1.length);
       
         for(int i=0; i<arrOfStr1.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr1[i]);
         }

         String[] arrOfStr2 = str.split("8",-3); 
         System.out.println("nOutput when limit is -ve");
         System.out.println("Number of substrings: "+arrOfStr2.length);
         
         for(int i=0; i<arrOfStr2.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr2[i]);
         }
         String[] arrOfStr3 = str.split("8",0); 
         System.out.println("nOutput when limit is 0");
         System.out.println("Number of substrings: "+arrOfStr3.length);
         
         for(int i=0; i<arrOfStr3.length; i++)
         {
             System.out.println("str["+i+"] : "+arrOfStr3[i]);
         }
    } 
}  

Output:

Output when limit is +ve
Number of substrings: 2
str[0] : 46
str[1] : -567-7388

Output when limit is -ve
Number of substrings: 4
str[0] : 46
str[1] : -567-73
str[2] : 
str[3] : 

Output when limit is 0
Number of substrings: 2
str[0] : 46
str[1] : -567-73

The above program demonstrates how the split() method works when the limit parameter is specified. As you see from the output:

  1. When the limit is 2, the number of substrings in the resulting array is two
  2. When the limit is -3, the input string is split into 4 substrings, including the trailing spaces
  3. When the limit is 0, the input string is split into 2 substrings because trailing spaces are excluded

This brings us to the end of this ‘Split Method in Java’ article. I have covered one of the fundamental topics of Java, on how to split strings using the split() method in Java. Hope you are clear with all that has been shared with you in this article.

Make sure you practice as much as possible and revert your experience.  

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this ‘How to Convert int to String in Java’ article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Split Method in Java: How to Split a String in Java?

edureka.co