$show=/label

Java String split() Examples on How To Split a String

SHARE:

A quick guide on how to split the string based on the delimiter. And also how to covert a String into String[] array with a given delimiter.

Java String split()

1. Overview


As part of String API features series, You'll learn how to split a string in java and also how to convert a String into String array for a given delimiter

This concept looks easy but quite a little tricky. You'll understand this concept clearly after seeing all the examples on the split() method.

The string split() method breaks a given string around matches of the given regular expression.
Java String split() Examples on How To Split a String

2. split() Syntax


The string class has two versions of the split() method. The first one takes an only regular expression. The second version takes two args with reg expression and limit is to limit the number of splits.

public String[] split​(String regex)

public String[] split​(String regex, int limit)

Parameters:

regex - the delimiting regular expression
limit - the result threshold

Returns always a String array.

3. public String[] split(String regex) Examples


In the below examples, you will see the different behavior with split(String regex) method

3.1 Example 1- How to split based on Special character '@'


Splitting based on '@' delimiter and exactly divides into how many times appears in the input string.

package com.javaprogramto.strings.split;

public class StringSplitExample1 {

    public static void main(String[] args) {
        String str = "java@program@to.com";

        String[] splitArray = str.split("@");

        for(String value : splitArray){
            System.out.println(value);
        }
    }
}

Output:

java
program
to.com

3.2 Example 2 - How to Split based on another String


Splitting based on the string "for".


public class StringSplitExample2 {

    public static void main(String[] args) {
        String str = "javaprogramto.comisfordevelopersandforfreshers";

        String[] splitArray = str.split("for");

        for(String value : splitArray){
            System.out.println(value);
        }
    }
}
Output:

Word "for" is appeared twice so the string is divided into 3 strings.

javaprogramto.comis
developersand
freshers

3.3 Example 3 - How to Split based on the empty space


package com.javaprogramto.strings.split;

public class StringSplitExample3 {

    public static void main(String[] args) {
        String str = "java programs for freshers";

        String[] spaceBasedSplitArray = str.split(" ");

        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:

java
programs
for
freshers

3.4 Example 4 - How to Split phone number based on delimiter '-'


package com.javaprogramto.strings.split;

public class StringSplitExample4 {

    public static void main(String[] args) {
        String phoneNo = "123-567-9080";

        String[] spaceBasedSplitArray = phoneNo.split("-");

        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:

123
567
9080

3.5 Example 5 - How to split Repeat Delimiter at end of string


If the delimiter is repeated at the end of the string then all trailing empty strings will be ignored. So returned String array will not have the empty spaces.

package com.javaprogramto.strings.split;

public class StringSplitExample5 {

    public static void main(String[] args) {
        String delimitetAtEndString = "1235-567-9080-1234-----";

        String[] spaceBasedSplitArray = delimitetAtEndString.split("-");

        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}


Output:

1235
567
9080
1234

3.6 Example 6 - How to split Repeat Delimiter in middle of the string


If the delimiter appears in the middle of String or in between start and end index then it considers the blank spaces.

package com.javaprogramto.strings.split;

public class StringSplitExample6 {

    public static void main(String[] args) {
        String delimitetAtEndString = "1235--------89";

        String[] spaceBasedSplitArray = delimitetAtEndString.split("-");

        System.out.println("returned array size : "+spaceBasedSplitArray.length);
        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:

returned array size : 9
1235







89

3.7 Example 7 - How to split Multiple Delimiters Using Regular Expression


Next, Look at the input string which is "hello,welcome to;java$program#to.com" is having many delimiters such as comma(,), white space, ;, $ and # symbols.

Below programs, show how to split based on assorted types of delimiters. You need to pass all of these characters inside square brackets [] then all are considered as a regular expression.

package com.javaprogramto.strings.split;

public class StringSplitExample7 {

    public static void main(String[] args) {
        String multipleDelimiters = "hello,welcome to;java$program#to.com";

        String[] spaceBasedSplitArray = multipleDelimiters.split("[, ;$#]");

        System.out.println("returned array size : "+spaceBasedSplitArray.length);
        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:

Observe the output and split with all special characters whatever is included in the pattern.

returned array size : 6
hello
welcome
to
java
program
to.com

4. public String[] split(String regex, int limit) Examples


Furthermore on this area, split(String regex, int limit) method works differently.

But, you need to understand that normal split(String regex) method internally calls the limit argument method split(String regex, int limit).

Limit parameter value plays an important role in this method and controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit is positive then the pattern will be applied at most limit - 1 times, the array's length will be no greater than the limit, and the array's last entry will contain all input beyond the last matched delimiter.

If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

If the limit is negative then the pattern will be applied as many times as possible and the array can have any length.

Now, it is time to see the more examples with limit option and understand in-depth.

4.1 Example 8 - split with limit value 0


If the limit value is passed as 0 then it works similar to the regular split(regex) method.
  
package com.javaprogramto.strings.split;

public class StringSplitLimitExample1 {
    public static void main(String[] args) {

        String withLimit0 = "Java:Program:to:.com";
        String[] spaceBasedSplitArray = withLimit0.split(":", 0);
        System.out.println("returned array size : "+spaceBasedSplitArray.length);
        for(String value : spaceBasedSplitArray){             System.out.println(value);
        }
    }

}

Output:

This produced the output as same as the regular method.
returned array size : 4

Java
Program
to
.com

4.2 Example 9 - split with limit value 1


Now, Understand how to split() method works with the different limit values. Pass the limit value as 1 and see the output.

package com.javaprogramto.strings.split;

public class StringSplitLimitExample1 {

    public static void main(String[] args) {
        String withLimit1 = "Java:Program:to:.com";

        String[] spaceBasedSplitArray = withLimit1.split(":", 1);

        System.out.println("returned array size with limit 1 : "+spaceBasedSplitArray.length);
        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:

returned array size with limit 1 : 1
Java:Program:to:.com

The above program produced the output without splitting. It just printed the only string and did not split based on the given delimiter colon(:) because we passed the limit value as 1. That indicates to the program to return string array should have only one value.

Look at the next example with a limit value 2.

4.3 Example 10 - split with limit value 2


package com.javaprogramto.strings.split;

public class StringSplitLimitExample1 {

    public static void main(String[] args) {
        String withLimit1 = "Java:Program:to:.com";

        String[] spaceBasedSplitArray = withLimit1.split(":", 1);

        System.out.println("returned array size with limit 1 : "+spaceBasedSplitArray.length);
        for(String value : spaceBasedSplitArray){
            System.out.println(value);
        }
    }
}

Output:
  
returned array size with limit 2 : 2
Java
Program:to:.com

In this program, we passed the limit value 2 to the split() method to produce the String array with two values. Even though the delimiter is present more than 2 times but it returns an array with two values only.

4.4 Example  11 -  String ends with a delimiter and with the limit value


If the string is ending with delimiters and all of these are discarded when split(regex) method is executed. But if you want to get those values also then need to pass the limit value.

See the below program with and without limit value. split(limit) method call returned string will have all blank values.

package com.javaprogramto.strings.split;

public class StringSplitLimitExample1 {

    public static void main(String[] args) {
        String stringWithEndingWithDelimiter = "Java:Program:to:.com:::";

        String[] arrayWithoutLimitValue = stringWithEndingWithDelimiter.split(":");

        System.out.println("returned array size without limit parameter : "+arrayWithoutLimitValue.length);
        for(String value : arrayWithoutLimitValue){
            System.out.println(value);
        }

        String[] arrayWithLimitValue = stringWithEndingWithDelimiter.split(":", 7);

        System.out.println("returned array size with limit parameter : "+arrayWithLimitValue.length);
        for(String value : arrayWithLimitValue){
            System.out.println(value);
        }
        System.out.println("Done");
    }
}

Output:
returned array size without limit parameter : 4
Java
Program
to
.com
returned array size with limit parameter : 7
Java
Program
to
.com



Done

4.5 Example  12 - Delimiter in the middle and end of the string (Negative limit value)


If the delimiter appears in middle and at the end of the string then the trailing values will be omitted with the split(regex) method.

In most of the cases, we do not know how many times delimiter will be at the end of the string. In this case, we need to pass the right value to the limit parameter then only it gets all values.

But, it is impossible to get the number of occurrences of a delimiter at the end of the string. So, handle such situations pass the negative index that holds all trailing values.
package com.javaprogramto.strings.split;

public class StringSplitLimitExample3 {

    public static void main(String[] args) {
        String stringWithEndingWithDelimiter = "Java:Program:::to:.com:::";

        String[] arrayWithoutLimitValue = stringWithEndingWithDelimiter.split(":");

        String[] arrayWithLimitValue = stringWithEndingWithDelimiter.split(":", -2);

        System.out.println("returned array size with limit parameter : "+arrayWithLimitValue.length);
        for(String value : arrayWithLimitValue){
            System.out.println(value);
        }
        System.out.println("Done");
    }
}
Output:

Java
Program


to
.com



Done

5. Validation with split() method


If you are expecting a particular number of values in a string then you can use the split() method.

String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");
 
This will split your string into 2 parts. The first element in the array will be the part containing the stuff before the -, and the 2nd element in the array will contain the part of your string after the -.

If the array length is not 2, then the string was not in the format: string-string. So, it throws IllegalArgumentException.

6. How to split string in java with dot in two ways

Example 13: Way 1 with dot


If you use directly as split("."), it will not work. Dot is a special character and so should use with double backslash's.
package com.javaprogramto.strings.split;

public class StringSplitExampleWithDot {

    public static void main(String[] args) {
        String multipleDelimiters = "hello.world.learn.java";

        String[] spaceBasedSplitArray = multipleDelimiters.split("\\.");

        System.out.println("Splitting string with dot way 1");
        for (String value : spaceBasedSplitArray) {
            System.out.println(value);
        }
    }
}
Output:

Splitting string with dot 
hello
world
learn
java

Example 14: Way 2 with dot using regular expression

package com.javaprogramto.strings.split;

public class StringSplitExampleWithDot {

    public static void main(String[] args) {
        String multipleDelimiters = "hello.world.learn.java";

        String[] spaceBasedSplitArray = multipleDelimiters.split("[.]");

        System.out.println("Splitting string with dot using regex 1");
        for (String value : spaceBasedSplitArray) {
            System.out.println(value);
        }

        multipleDelimiters = "welcome.to.the.javaprogramto.com";

        spaceBasedSplitArray = multipleDelimiters.split("[.]");

        System.out.println("\nSplitting string with dot using regex 2 \n");
        for (String value : spaceBasedSplitArray) {
            System.out.println(value);
        }


    }
}

Output:

Splitting string with dot using regex 1
hello
world
learn
java

Splitting string with dot using regex 2 

welcome
to
the
javaprogramto
com

7. How to split string in java with slash

When working with file locations you want to find the no of folder in the path. You can use split() method to find the folders count.

package com.javaprogramto.strings.split;

public class StringSplitExampleWithSlash {

    public static void main(String[] args) {
        String fileLocation = "/Users/javaprogramto/Documents/course/blog/workspace/CoreJava/split.java";

        String[] slashBasedSplitArray = fileLocation.split("/");

        System.out.println("Splitting string with dot using regex 1");
        for (String value : slashBasedSplitArray) {
            System.out.println(value);
        }

        System.out.println("No of folders in the path : " + (slashBasedSplitArray.length - 1));


    }
}
Output:

Splitting string with dot using regex 1

Users
javaprogramto
Documents
course
blog
workspace
CoreJava
split.java
No of folders in the path : 8

8. How to split String in Java by WhiteSpace or tabs? 

You can use the whitespace regex: str = "Hello baby, welcome to sweet world"; String[] splited = str. split("\\s+"); This will cause any number of consecutive spaces to split your string into tokens

package com.javaprogramto.strings.split;

public class StringSplitExampleWithSpace {

    public static void main(String[] args) {
        String coutries = "TR TM TC TV UG UA AE GB UM US UY UZ VU VE";

        String[] spaceBasedSplitArray = coutries.split(" ");

        System.out.println("Splitting string with space 1");
        for (String value : spaceBasedSplitArray) {
            System.out.println(value);
        }

        coutries = "TUR TKM TCA TUV UGA UKR ARE GBR UMI USA URY UZB VUT VEN";

        spaceBasedSplitArray = coutries.split("\\s+");

        System.out.println("\nSplitting string with space 2");
        for (String value : spaceBasedSplitArray) {
            System.out.println(value);
        }
    }
}

Output:

Splitting string with space 1
TR
TM
TC
TV
UG
UA
AE
GB
UM
US
UY
UZ
VU
VE

Splitting string with space 2
TUR
TKM
TCA
TUV
UGA
UKR
ARE
GBR
UMI
USA
URY
UZB
VUT
VEN

9. How To Split a Java String by the pipe symbol using split(“|”)


Splitting string with pipe delimiter, you can use pattern "\\|" or Pattern.quote("|") to string split() method.

package com.javaprogramto.strings.split;

import java.util.regex.Pattern;

public class StringSplitExampleWithPipe {

    public static void main(String[] args) {
        String countryNames = "Turkey|Turkmenistan|Turks and Caicos Islands (the)|Tuvalu|Uganda|Ukraine|United Arab Emirates (the)|United Kingdom of Great Britain and Northern Ireland (the)|United States Minor Outlying Islands (the)|United States of America (the)|Uruguay|Uzbekistan|Vanuatu|Venezuela (Bolivarian Republic of)";

        String[] pipeBasedSplitArray = countryNames.split("\\|");

        System.out.println("Splitting string with pipe 1");
        for (String value : pipeBasedSplitArray) {
            System.out.println(value);
        }

        String countryCodes = "792|795|796|798|800|804|784|826|581|840|858|860|548|862";

        pipeBasedSplitArray = countryCodes.split(Pattern.quote("|"));

        System.out.println("\nSplitting string with pipe 2");
        for (String value : pipeBasedSplitArray) {
            System.out.println(value);
        }
    }
}

Output:

Splitting string with pipe 1
Turkey
Turkmenistan
Turks and Caicos Islands (the)
Tuvalu
Uganda
Ukraine
United Arab Emirates (the)
United Kingdom of Great Britain and Northern Ireland (the)
United States Minor Outlying Islands (the)
United States of America (the)
Uruguay
Uzbekistan
Vanuatu
Venezuela (Bolivarian Republic of)

Splitting string with pipe 2
792
795
796
798
800
804
784
826
581
840
858
860
548
862





6. Conclusion


In this article, you've seen how to split a string in java with a split() method

How the split() method works with different input values.
All are shown with examples of programs with limit value positive, zero and negative value.

Examples shown are over GitHub.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,5,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,77,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,53,Java 8 Difference,2,java 8 Stream Examples,2,Java 9,1,Java Conversions,12,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,13,String,57,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java String split() Examples on How To Split a String
Java String split() Examples on How To Split a String
A quick guide on how to split the string based on the delimiter. And also how to covert a String into String[] array with a given delimiter.
https://1.bp.blogspot.com/-3QOgaXsZsnM/XxhawVaGrAI/AAAAAAAAC2o/faerxv5IPzU7_H0s7gbMFk5AKLfey1-ZgCLcBGAsYHQ/w400-h185/Java%2BString%2Bsplit%2528%2529%2BExamples%2Bon%2BHow%2BTo%2BSplit%2Ba%2BString.png
https://1.bp.blogspot.com/-3QOgaXsZsnM/XxhawVaGrAI/AAAAAAAAC2o/faerxv5IPzU7_H0s7gbMFk5AKLfey1-ZgCLcBGAsYHQ/s72-w400-c-h185/Java%2BString%2Bsplit%2528%2529%2BExamples%2Bon%2BHow%2BTo%2BSplit%2Ba%2BString.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/07/java-string-split-examples-on-how-to-split-a-string.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/07/java-string-split-examples-on-how-to-split-a-string.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content