有一篇文本,文本中有中文跟英文,词与词之间用空格符分开,如:“支持 USB 充电 插上 usb线 电池格 变成 二格 没 确认”。文本已读到java.io.Reader中了,如何从该Reader中把每个词读出来?
我写的一个程序效果很不好: private Reader input; //输入文本
private String currentToken; //读取的一个词语
private void readNextToken() { StringBuffer buf = new StringBuffer();
boolean endReached = false; //判断是否达到文本结尾
int in = 0; try { // Read from the stream, until a letter occurs in = input.read();
char ch = (char) in; while ((in != -1) && (Character.isWhitespace(ch))){
in = input.read();
ch = (char) in;
} if (in != -1)
buf.append(ch); // Read from the stream, util a non-letter occurs while ((in != -1) && !(Character.isWhitespace(ch))) { in = input.read();
ch = (char) in; if (!Character.isWhitespace(ch))
buf.append(ch); }
} catch (Exception e) {
endReached = true; } if (in == -1)
endReached = true; if (endReached) { // If the stream ended with a non-empty token, this is the last
// token, otherwise there is no more token. if (buf.length() > 0)
currentToken = buf.toString();
else
currentToken = null; return;
} else { // if the end of the stream has not been reached yet, simply store
// the extracted token.
currentToken = buf.toString();
return;
} }
请大侠帮忙!!大侠救救我吧!!
我写的一个程序效果很不好: private Reader input; //输入文本
private String currentToken; //读取的一个词语
private void readNextToken() { StringBuffer buf = new StringBuffer();
boolean endReached = false; //判断是否达到文本结尾
int in = 0; try { // Read from the stream, until a letter occurs in = input.read();
char ch = (char) in; while ((in != -1) && (Character.isWhitespace(ch))){
in = input.read();
ch = (char) in;
} if (in != -1)
buf.append(ch); // Read from the stream, util a non-letter occurs while ((in != -1) && !(Character.isWhitespace(ch))) { in = input.read();
ch = (char) in; if (!Character.isWhitespace(ch))
buf.append(ch); }
} catch (Exception e) {
endReached = true; } if (in == -1)
endReached = true; if (endReached) { // If the stream ended with a non-empty token, this is the last
// token, otherwise there is no more token. if (buf.length() > 0)
currentToken = buf.toString();
else
currentToken = null; return;
} else { // if the end of the stream has not been reached yet, simply store
// the extracted token.
currentToken = buf.toString();
return;
} }
请大侠帮忙!!大侠救救我吧!!
解决方案 »
- 这句代码没有意义吗?为何提示我:Null pointer access?
- 【100分】求教。图像识别方面的技术
- 那种数据没读完整前只显示图片loading。。。的效果是如何实现的?
- 一个奇怪的线程锁定问题
- 大家推荐几本JSP的书
- java 中 now() 函数需要包含什么包才能用
- 请教:java中能不能向VC中__LINE__宏一样获取当前的行号,__FILE__获取当前的文件名?
- 装了JBuilder 9.0后,以前的sdk 1.41还可以照常用吗?谢谢!
- 小弟最近刚看完《java编程思想》,目前比较迷茫,还不知道自己到底应该往哪个方向发展?
- java工作手册之类的书
- 简单问题
- 关于一个异常~~·
str.split(" ");
用空格分开就行了!
in = input.read();
char ch = (char) in;//读取一个字符,转为char型。是不是英文字符跟中文字符字节数不一样啊?