import java.util.StringTokenizer;
public class Token {
public static void main(String []args)
{
String s="hello! Nice to meet you";
StringTokenizer stk=new StringTokenizer(s," !");//感叹号前有个空格,说明是以空格和!为分隔符
int n=stk.countTokens();//获取分割单词数量
System.out.println("共有多少个单词?答:"+n);
while(stk.hasMoreTokens())
{
System.out.println(stk.nextToken());
}
}
}
结果:
共有多少个单词?答:5
hello
Nice
to
meet
you
分解字符串的话其实建议使用String 自带的split函数
import java.util.StringTokenizer;
public class Token {
public static void main(String []args)
{
String s="hello!Nice to meet you";
// StringTokenizer stk=new StringTokenizer(s," !");//感叹号前有个空格,说明是以空格和!为分隔符
// int n=stk.countTokens();//获取分割单词数量
// System.out.println("共有多少个单词?答:"+n);
// while(stk.hasMoreTokens())
// {
// System.out.println(stk.nextToken());
// }
String temp[]=s.split("!| ");
for(int i=0;i<temp.length;i++)
{
System.out.println(temp[i]);
}
}
}
结果:
hello
Nice
to
meet
you