Instead of using the old StringTokenizer class, a simple trick is to use the String.split method.
Expand|Select|Wrap|Line Numbers
- 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.g Expand|Select|Wrap|Line Numbers
- 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 Expand|Select|Wrap|Line Numbers
- String name = "java.sql.Date";
- String[] s = name.split("\\.", 1);
- System.out.println(Arrays.toString(s));