У меня есть метод, который должен учитывать появление слова в предложении и возвращать результаты. По какой-то причине это не считается. Код всегда возвращает 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;
}
Может ли кто-нибудь сказать мне, что случилось с моим методом?
Я просто взял ваш код и удалил ваши -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.
Ваша подстрока выключена, и ваша проверка положения циклы также неверна. Когда я изменю свой метод,
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
Лучше всего проверить "пространство", как каждое пространство, с которым нужно столкнуться... count++..... и вы также можете проверить "\n" в чеке и завершить цикл at\0 строка null знак !!
Вы можете попробовать этот код:
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;
}
Я бы использовал regex
Matcher m= Pattern.compile("\\b" + word + "\\b").matcher(sentence);
while(m.find()) {
count++;
}
Использование метода Collections.frequency()
в List
слов обойдует всю потребность в отслеживании счета:
public static int countOccurance (String word, String sentence) {
List<String> words = Arrays.asList(sentence.split(" "));
return Collections.frequency(words,word);
}
Потому что другие уже объяснили, почему ваш текущий код не работает, я хотел бы использовать этот ответ, чтобы сделать рекомендацию. Я лично рекомендовал бы использовать Java regex 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;
}
Надеюсь, это поможет.