Java Reference
In-Depth Information
Output 1 was: null
Output 2 was: null
Output 3 was: D
Output 4 was: E
See Also
Many occurrences of StringTokenizer may be replaced with regular expressions (see
Chapter 4 ) with considerably more flexibility. For example, to extract all the numbers from a
String , you can use this code:
Matcher toke = Pattern.compile("\\d+").matcher(inputString);
while (toke.find( )) {
String courseString = toke.group(0);
int courseNumber = Integer.parseInt(courseString);
...
This allows user input to be more flexible than you could easily handle with a StringToken-
izer . Assuming that the numbers represent course numbers at some educational institution,
the inputs “471,472,570” or “Courses 471 and 472, 570” or just “471 472 570” should all
give the same results.
Putting Strings Together with StringBuilder
Problem
You need to put some String pieces (back) together.
Solution
Use string concatenation: the + operator. The compiler implicitly constructs a StringBuild-
er for you and uses its append() methods (unless all the string parts are known at compile
time). Better yet, construct and use it yourself.
Search WWH ::




Custom Search