Java字符串中找单词出现个数?

qusthuanglong 2010-05-21 10:52:14
统计这篇短文用了多少个单词“to”。
There was an American couple who had no children, so they wanted to adopt a child. Finally, an orphanage contacted them, saying, "We have a baby for adoption.It's a Russian orphan." The couple was delighted and went to bring the baby home.
On the way home, they stopped by a university to enroll in a Russian course. "Why do you want to learn Russian? The English that we speak is a very good language," the university secretary asked."Well, we just adopted a Russian baby. When he begins to speak Russian in a few years, we are afraid that we might not be able to understand him," the couple replied.



考虑的情况: 句子首字母是to,一个单词里有to,比如too;
...全文
366 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
chan10 2010-05-22
  • 打赏
  • 举报
回复
还是用正则表达式吧。
简单易懂。
sxg263 2010-05-22
  • 打赏
  • 举报
回复
import java.io.*;
public class CountChar {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileReader fileIn=null;
try{
fileIn=new FileReader("D:\\java\\1.txt");
}catch(FileNotFoundException e){
System.out.println("找不到文件,程序将终止!");
e.printStackTrace();
System.exit(-1);
}
char[] cc=new char[1024];

try{
fileIn.read(cc);
}catch(IOException e){
System.out.println("文件读入错误!");
fileIn.close();
}
String str1=new String(cc);
String[] strArray=new String[1024];
strArray=str1.split(" to ");
int count=strArray.length;
System.out.println(""+count);

}

}


没考虑开头结尾,和to为一句话的结尾情况(如 to, to?)
太困了,睡了。
zhuwen9 2010-05-22
  • 打赏
  • 举报
回复


String str = "TO,to,toto,aaaaa,too,ato";
int times = str.length() - str.replaceAll("[To||to]","").length();
System.out.print("to出现的次数"+times/2);
hujixianghujixiang 2010-05-21
  • 打赏
  • 举报
回复
同意楼上的
东子于 2010-05-21
  • 打赏
  • 举报
回复
同意楼上的
paullbm 2010-05-21
  • 打赏
  • 举报
回复
用正则匹配就OK了!

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧