查找单词个数案列实现(字符串流)
案列:写一个字符串,判断单词个数?
分析:可以字符串流来完成,根据字符串流得到一个StreamTokenizer
(流标记器对象),
这个对象有下列常量和方法:
TT_EOF
:指示流末尾已被读取的常量
TT_WORD
:指示已读取单词标记的常量
int nextToken()
;从输入流中解析下一个对象
int ttype()
:在调用nextToken方法后,此字段包含刚刚读取的令牌的类型
代码演示:
public class Test12 {
private static void stringReader() {
StringReader reader = new StringReader("what is your name");
// 流标记器
StreamTokenizer st = new StreamTokenizer(reader);
int count = 0;
while (st.ttype != StreamTokenizer.TT_EOF) {
try {
if (st.nextToken() == StreamTokenizer.TT_WORD) {
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("count=" + count);//count=4
}
public static void main(String[] args) {
stringReader();
}
}