我有一个方法应该计算句子中单词的出现并返回结果。由于某种原因,它不算数。代码始终返回0
。
这是代码。
public static int countOccurance (String word, String sentence) {
int count = 0;
for (int i = 0; i != sentence.length()-word.length()-2; i++) {
if (sentence.substring(i, i+word.length()-1).equalsIgnoreCase(word)) {
count++;
}
}
return count;
}
有谁能告诉我我的方法有什么问题?
答案 0 :(得分:1)
您的子字符串已关闭,您的循环位置检查也不正确。当我将你的方法改为时,
public static int countOccurance(String word, String sentence) {
int count = 0;
for (int i = 0; i + word.length() < sentence.length(); i++) {
if (sentence.substring(i, i + word.length()).equalsIgnoreCase(
word)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countOccurance("Hello", "hello hello world"));
System.out.println(countOccurance("Fi", "Fee Fi Fum"));
}
它输出预期的
2
1
答案 1 :(得分:1)
我刚拿走你的代码并删除你的-1和-2,因为我不明白为什么他们在那里。
public static int countOccurance (String word, String sentence) {
int count = 0;
for (int i = 0; i != sentence.length()-word.length(); i++) {
if (sentence.substring(i, i+word.length()).equalsIgnoreCase(word)) {
count++;
}
}
return count;
}
试过这个。
String sentence = "yakkity yak yak yak attack";
String word = "yak";
int wc = countOccurance (word, sentence);
System.out.println("The string \""+sentence+"\" contains the word "+word+" "+wc+" times.");
结果:
The string "yakkity yak yak yak attack" contains the word yak 4 times.
答案 2 :(得分:0)
最好是检查&#34; &#34;空间,,,因为每个空间都要遇到...计数++ ..... 你也可以查看&#39; \ n&#39;在检查案件中 并使循环结束于\ 0 string null character !!
答案 3 :(得分:0)
我会使用正则表达式
Matcher m= Pattern.compile("\\b" + word + "\\b").matcher(sentence);
while(m.find()) {
count++;
}
答案 4 :(得分:0)
在Collections.frequency()
个单词上使用List
方法,避免了自己跟踪计数器的全部需求:
public static int countOccurance (String word, String sentence) {
List<String> words = Arrays.asList(sentence.split(" "));
return Collections.frequency(words,word);
}
答案 5 :(得分:0)
因为其他人已经说明了为什么您当前的代码不起作用,我想使用这个答案来提出建议。我个人建议使用Java的正则表达式API来解决这个问题。使用类似下面的内容;
public static int countOccurance (String regex, String sentence) {
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while(m.find()) count++;
return count;
}
我希望这会有所帮助。
答案 6 :(得分:0)
您可以尝试以下代码:
public static void main(String[] args){
String sentence = "Hello truc, Hello machi, and Hello all !";
final String word = "hello";
System.out.println(count(sentence.toLowerCase(), word.toLowerCase()));
}
public static int count(String sentence, String word){
int cpt = 0;
while(sentence.contains(word)){
cpt++;
sentence = sentence.substring(sentence.indexOf(word) + word.length());
}
return cpt;
}