How to Split String in Java with Example

Here you will learn how to split string in java.

We can split string in Java using split() method of java.lang.String class. It takes a regular expression as an argument and returns an array of strings.

Syntax:

 

How to Split String in Java with Example

Split String in Java Example

Below program will split the string by space.

 

Output

I
Love
Java
Programming

 

There are few special characters like ., ?, |, +, etc. and some escape characters like \n, \t, \b, etc. that must be escaped before using as a regular expression in split() method. We can escape them by using two backslash characters i.e. \\.

For example if you want to split the string by + character then you have to use \\+ as a regular expression in split() method.

 

Java String Split with Length

You can split a string by regular expression along with length using another variant of split() method.

 

Syntax:

 

Example

 

Output

I
Love Java Programming

 

As you can see in above example that the string is split into 2 parts because we have used length as 2.

 

Comment below If you found anything incorrect or have doubts related to above Java split string tutorial.

Leave a Comment

Your email address will not be published. Required fields are marked *