Java中的StringTokenizer类用于将字符串分解为令牌。
例子:
StringTokenizer对象在内部维护要标记化的字符串中的当前位置。某些操作会将当前位置提前经过处理的字符。
通过获取用于创建StringTokenizer对象的字符串的子字符串来返回令牌。
构造函数:
StringTokenizer(String str) :
str is string to be tokenized.
Considers default delimiters like new line, space, tab, carriage return and form feed.
StringTokenizer(String str, String delim) :
delim is set of delimiters that are used to tokenize
the given string.
StringTokenizer(String str, String delim, boolean flag):
The first two parameters have same meaning. The flag
serves following purpose.
If the flag is false, delimiter characters serve to
separate tokens. For example, if string is "hello geeks"
and delimiter is " ", then tokens are "hello" and "geeks".
If the flag is true, delimiter characters are
considered to be tokens. For example, if string is "hello
geeks" and delimiter is " ", then tokens are "hello", " "
and "geeks".
/* A Java program to illustrate working of StringTokenizer
class:*/
import java.util.*;
public class NewClass
{
public static void main(String args[])
{
System.out.println( "Using Constructor 1 - " );
StringTokenizer st1 =
new StringTokenizer( "Hello Geeks How are you" , " " );
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println( "Using Constructor 2 - " );
StringTokenizer st2 =
new StringTokenizer( "JAVA : Code : String" , " :" );
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println( "Using Constructor 3 - " );
StringTokenizer st3 =
new StringTokenizer( "JAVA : Code : String" , " :" , true );
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
输出:
Using Constructor 1 -
Hello
Geeks
How
are
you
Using Constructor 2 -
JAVA
Code
String
Using Constructor 3 -
JAVA
:
Code
:
String
我们将很快在单独的文章中讨论StringTokenizer的方法。
参考:
https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html