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.
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:
javaprogramto.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.comisdevelopersandfreshers
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:
javaprogramsforfreshers
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:
123556790801234
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 : 9123589
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 : 6hellowelcometojavaprogramto.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 : 4JavaProgramto.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 : 2JavaProgram: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:JavaProgramto.comDone
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
10. 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.
No comments:
Post a Comment
Please do not add any spam links in the comments section.