Java Reference
In-Depth Information
When run, this prints the following:
C:> java strings.SubStringDemo
Java is great.
is great.
is
is great.
C:>
Breaking Strings Into Words
Problem
You need to take a string apart into words or tokens.
Solution
To accomplish this, construct a StringTokenizer around your string and call its methods
hasMoreTokens() and nextToken() .
Or, use regular expressions (see Chapter 4 ).
Discussion
The easiest way is to use a regular expression; we'll discuss these in Chapter 4 , but for now,
a string containing a space is a valid regular expression to match space characters, so you can
most easily split a string into words like this:
for
for ( String word : some_input_string . split ( " " )) {
System . out . println ( word );
}
If you need to match multiple spaces, or spaces and tabs, use the string "\s+" .
Another method is to use StringTokenizer . The StringTokenizer methods implement the
Iterator interface and design pattern (see Using Iterators or Enumerations for Data-
Independent Access ):
Search WWH ::




Custom Search