Breaking up a string
Instead of using the old StringTokenizer class, a simple trick is to use the String.split method.
prints
This
is
a
string
The split method returns an array of tokens and takes a string that represents regular expression as argument. In the above example I gave " " (space) as the argument so the string was split on space.
Note
Instead of using the old StringTokenizer class, a simple trick is to use the String.split method.
Code:
String string = "This is a string";
String[] tokens = string.split(" ");
for(String s: tokens) {
System.out.println(s);
}
This
is
a
string
The split method returns an array of tokens and takes a string that represents regular expression as argument. In the above example I gave " " (space) as the argument so the string was split on space.
Note
- If the expression does not match any part of the input then the resulting array has just one element, namely this string.
- to split on special characters you need to escape them using the \ character e.gCode:
String name = "java.sql.Date"; String[] s = name.split("\\."); System.out.println(Arrays.toString(s)); - There are actually two split methods in the String class. The second one takes a regular expression and an integer representing the limit e.g returns the array with only one elementCode:
String name = "java.sql.Date"; String[] s = name.split("\\.", 1); System.out.println(Arrays.toString(s));
Comment