In this article, we’ll go through how you can use Java string split methods of String class.
1. Java String Split Method with a Regex
This method will split the string based on the regex you provided and return an array of strings with the items you want. Of course, the regex that matched will be excluded.
Below you can find a string split example in java, where we use the comma as a delimiter:
String namesString = "Georgios,Nikolaos,Ioannis,Dimitris"; String[] namesArray = namesString.split(","); for(String name : namesArray) System.out.println(name);
In the above example, we splitted namesString
based on a comma; this will print:
Georgios Nikolaos Ioannis Dimitris
But what if we wanted to use a regex?
String countriesString = "Greece3USA6UK9"; String[] countriesArray = countriesString.split("[0-9]"); for(String country : countriesArray) System.out.println(country);
In the example above, we wanted to split the countries based on whether a number between 0 and 9 exists between them. Therefore, we pass the regex [0-9]
as a parameter and this will print
Greece USA UK
Moreover, you need to be careful and escape special regex characters such as . ? * [
as the result will not be the expected.
For instance, the following string split example uses a dot as a delimiter but you can see it won’t work without escaping the special characters.
String countriesString = "Greece.USA.UK"; String[] countriesArray = countriesString.split("."); for(String country : countriesArray) System.out.println(country);
In order to remedy this, we have to change Line 2 as shown below:
String[] countriesArray = countriesString.split("\\.");
2. Java String Split Method with a Regex and a Limit
First of all, the difference with the previous method is that you can specify how many times you want to apply the split.
Furthermore, the limit argument is exclusive and as a result, if you set a limit to be n
, this means that you will apply the split n-1
times.
For example, let’s say we want to split the string "You;Learn;Code;is;the;Best"
in 3 parts, the first will be "You"
, the second "Learn"
and the third "Code;is;the;Best
.
String ylc = "You;Learn;Code;is;the;Best"; String[] ylcSplitted = ylc.split(";", 3); for(String word : ylcSplitted) System.out.println(word);
This will print:
You Learn Code;is;the;Best
Note that if we choose a number less than or equal to zero as the limit, the limit will be ignored and the result will be the same as with the split(String regex)
.
String ylc = "You;Learn;Code;is;the;Best"; String[] ylcSplitted = ylc.split(";", -2); for(String word : ylcSplitted) System.out.println(word);
As a result, this will print:
Code Learn Hub is the Best
3. Conclusion
By now you should be able to use the two split methods that the String class provides. You can find the source code on our GitHub page.