public class Numberofwords {
public static void main(String[] args) {
String str = "Hello World abc Hello hello";
// 截取字符串 第一个包含的 第二个不包含
Numberofwords test = new Numberofwords();
int count = test.wordCount(str,"hello");
System.out.println(count);
// String str ="hello hello wrod wrod wrod wrod wrod wrod hello";
// String str1 = "hello";
// String replace = str.replace(str1, "");
// int replaceTest = str.length() - replace.length();
// int count = replaceTest / str1.length();
// System.out.println(count);
}
public int wordCount(String Test, String word) {//返回值为文章和所选定的单词
// 1、先把文章打散成数组
String[] st= Test.split(" ");//文章遇见空格时,分成一个数组,遇到空格时分成一个数组,从而把文章分为一个一个的数组。
int res = 0;
for (int i = 0; i < st.length; i++) {
if (st[i].equalsIgnoreCase(word)){//判断数组是否等于所选择的词语
res++;
}
}
return res;
}
}
使用Java来实现统计单词出现的次数两种方法
最新推荐文章于 2024-05-31 22:04:23 发布
该代码示例展示了如何在Java中计算一个字符串中特定单词的出现次数。通过split方法将字符串分解为单词数组,然后遍历数组并比较每个单词,实现对目标单词的计数功能。
2132

被折叠的 条评论
为什么被折叠?



