Tutorials

Java String


Java String Split


String split() method breaks the input String against the provided regular expression and returns String array.

Type Signature

public String split(String regex)

public String split(String regex, int limit) 

 

Example

String strDemo → "Break me to words"

Apply split on above String strDemo which will return

String []strArray  →  {"Break", "me", "to", "words"}

 

The above concept will be reflected in the below given source code as well. Let’s have a look.

 

package string;

 

public class splitDemo {

 

      public static void main(String[] args) {

            String strDemo = "Break me to words";

           

            String[] strArray = strDemo.split("\\s");

           

            for(String s : strArray){

                  System.out.println(s);

            }

 

      }

}

OUTPUT:

Break

me

to

words

 

Important points:

  • split() method returns PatternSyntaxException if pattern for regular expression is invalid.
  • After splitting the given String, split() stores each word in String array.


Please Share this page
Views : 130
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!