Java Reference
In-Depth Information
StrTokDemo3.java
StringTokenizer st
=
new
new
StringTokenizer
(
"Hello, World|of|Java"
,
", |"
,
true
true
);
while
while
(
st
.
hasMoreElements
( ))
System
.
out
.
println
(
"Token: "
+
st
.
nextElement
( ));
and you get this output:
C:\>
java strings.StrTokDemo3
Token: Hello
Token: ,
Token:
Token: World
Token: |
Token: of
Token: |
Token: Java
C:\>
This isn't how you'd like
StringTokenizer
to behave, ideally, but it is serviceable enough
most of the time.
Example 3-1
processes and ignores consecutive tokens, returning the res-
ults as an array of
String
s.
Example 3-1. StrTokDemo4.java (StringTokenizer)
public
public class
class
StrTokDemo4
StrTokDemo4
{
public
public final
final static
static
int
int
MAXFIELDS
=
5
;
public
public final
final static
static
String DELIM
=
"|"
;
/** Processes one String, returns it as an array of Strings */
public
public static
static
String
[]
process
(
String line
) {
String
[]
results
=
new
new
String
[
MAXFIELDS
];
// Unless you ask StringTokenizer to give you the tokens,
// it silently discards multiple null tokens.
StringTokenizer st
=
new
new
StringTokenizer
(
line
,
DELIM
,
true
true
);
int
int
i
=
0
;
// stuff each token into the current slot in the array.
while
while
(
st
.
hasMoreTokens
()) {
String s
=
st
.
nextToken
();