用java写一个统计字符串中指定单词的个数

要求:任意的源字符串。
匹配的单词以参数方式传入。
以整数形式返回结果。

比如说源字符串是str="bookabcbookadbook";
str=" "+str+" ";
单词是s="book";
直接输出str.split(s).length-1就是单词的个数。
原理就是字符串前后都加空格以后,再用你要查找的单词把字符串分成数组,数组元素的个数减1,就是单词的个数了。当然,首先要用contains() 方法判断一下字符串是否已经包含要找的单词。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-22
public static int getCount(String str,String key)
{
int count=0;//计数器记录出现的次数
int shift=key.length(); //角标偏移位
int i=0;//字符串角标位置
while(i<=str.length()-shift)//循环条件当字符串角标位置距离结尾的长度不小于key的长度
{
String temp=str.substring(i,i+shift);

if(key.equals(temp))
{
count++;
i+=shift;
continue;
}
i++;
}
return count;
}
第2个回答  2012-12-22
最简单的办法就是用replace替换那个单词,比如替换成*,然后split("*")得到一个数组,数组长度减去一就是单词个数。
第3个回答  2012-12-22
public int count(String S,String s){//S--源字符串,s--匹配的单词
int count=0;
int n=0;
while(n<S.length()-1){
if(S.indexOf(s,n)!=-1){
count++;
n=S.indexOf(s,n)+s.length();
}
else{break;}
}
return count;
}
第4个回答  2012-12-21
public static int test(String src, String s) {
return (src.length() - src.replace(s, "").length()) / s.length();
}

感觉比较偷懒追问

亲,敢写完整的吗?

package com.oracle;
public class test01 {
public static void test01(){
String str=("dfghdshfrtdhgffdhfdhhtfnxsadgh");
int a = str.length()-str.replaceAll("f", "").length();
public static void main(String[] args) {

test01();
}

}

追答

这只是一个静态方法,放类里就能用的,还要怎么完整……

外面的类也需要?

追问

这个这个,初学者啊,很多东西都不是很懂的

追答

额外提一下,用split比这个还要简单一些,不过replaceAll和split的参数都是正则表达式,如果你用那个需要把s处理一下,变成Pattern.quote(s),repalce的参数只是普通的字符串。

再者都没判断空值之类的东西,需要的话自己加吧

追问

说实话吧,嗯,你那个代码没有看懂,额,我才学java2天!

追答

无语了……

把要统计的字符串从源字符串中删除,然后算出长度差值,除以统计字符串长度,最终就是个数。
split那个是分割字符串成数组,简单说来说是"ababa"按"b"分割得到个长度为3个数组,全是"a",减1后就是"b"的个数,问题是如果按空字符串""分割得到长度为6的数组,第一个为空串,其余是那5个字母,所以需要先判断一下

追问

public static void test01(){
System.out.println("输入字符串:");
Scanner sc=new Scanner(System.in);
String s=sc.next();
String str=(s);
int a = str.length()-str.replaceAll("f", "").length();
System.out.println("f"+"出现的次数是:"+a);

}
我是这么想的嘛,自己输入字符串,和需要匹配的单词,然后系统给出个数,然后我就不知道怎么写了,英雄,救命啊!

追答

public class Test {
public static void main(String[] args) {
String src = "abcabcabc";
System.out.println("输入字符串:");
Scanner sc=new Scanner(System.in);
String s=sc.next();
int count = test(src, s);
System.out.println(src + "中" + s + "出现的次数是:" + count);
}
public static int test(String src, String s) {
return (src.length() - src.replace(s, "").length()) / s.length();
}
}

相似回答