Abstract
I will describe how to split a string in Java using the split() method.
Example 1: colon
Suppose you are given the string “23:59:48” and want to access the numbers 23, 59 and 48 between the colons. In Java you can use the String method split() where you have to pass the delimiter to the method. Run the code below.
String time = "23:59:48";
String[] numbers = time.split(":");
for(String s : numbers){
System.out.println(s);
}
The delimiter is “:” and is passed to split(). The method returns a String array which contains the numbers 23, 59, and 48.
Example 2: slash
Here we are given a string with a slash as delimiter.
String path = "C:/User/Programs/Java/Project/april";
String[] folders = path.split("/");
for(String s : folders){
System.out.println(s);
}
Example 3: comma and space
String people = "Alice, Bob, Charlie, Dan, Eve";
String[] names = people.split(", ");
for(String s : names){
System.out.println(s);
}
String str = "Hello! This is a tutorial!";
String[] words = str.split("\\s");
// or we can use str.split(" ")
for(String s : words){
System.out.println(s);
}
Example 4: Special cases
For some characters you have to use another notation, e.g. for a dot you cannot just simply call split(“.”). The reason is that we pass a regular expression to the split() method and “.” has a special meaning. Instead we have to use split(“\\.”).
// split(".") does not work since the dot has a
// a special meaning for regular expressions
String date = "21.03.2013";
String[] nums = date.split("\\.");
for(String s : nums){
System.out.println(s);
}
// Note: In the string we used double backslashes
// instead of backslashes.
// The reason is that a single backslash is reserved
// for escape sequences
String path_windows = "C:\\User\\Programs\\Java\\Project\\march";
String[] folders_windows = path_windows.split("\\\\");
for(String s : folders_windows){
System.out.println(s);
}
String year = "jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec";
String[] months = year.split("\\|");
for(String s : months){
System.out.println(s);
}
Note:
I found this useful for problem 158C – Cd and pwd commands on Codeforces.
References
[1] Java String Split Example
[2] How to String Split Example in Java – Tutorial
[3] A little tutorial about String.split()