Подтвердить что ты не робот

Подсчитайте количество появлений слова в строке

Я новичок в Java Strings, проблема в том, что я хочу подсчитывать происшествия определенного слова в String. Предположим, что моя строка:

i have a male cat. the color of male cat is Black

Теперь я не хочу разбить его, поэтому я хочу найти слово "кошка". это происходит два раза в моей строке!

Я пытаюсь:

int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);

он дает мне 46 счетчиков! Итак, какое решение?

4b9b3361

Ответ 1

Вы можете использовать следующий код:

String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
    i++;
}
System.out.println(i); // Prints 2

Демо

Что он делает?

Он соответствует "male cat".

while(m.find())

указывает, выполняет ли что-либо внутри цикла, а m находит совпадение. И я увеличиваю значение i на i++, поэтому, очевидно, это дает число male cat, которое получила строка.

Ответ 2

Если вам просто нужен счетчик "male cat", я бы просто сделал это следующим образом:

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

и если вы хотите убедиться, что "female cat" не сопоставляется, используйте \\b границы слова в разделенном регулярном выражении:

int c = str.split("\\bmale cat\\b").length - 1;

Ответ 3

StringUtils в apache commons-lang есть метод CountMatches, чтобы подсчитывать количество вхождений одной строки в другой.

   String input = "i have a male cat. the color of male cat is Black";
   int occurance = StringUtils.countMatches(input, "male cat");
   System.out.println(occurance);

Ответ 4

Версия Java 8:

    public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
    return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}

Ответ 5

с помощью indexOf...

public static int count(String string, String substr) {
    int i;
    int last = 0;
    int count = 0;
    do {
        i = string.indexOf(substr, last);
        if (i != -1) count++;
        last = i+substr.length();
    } while(i != -1);
    return count;
}

public static void main (String[] args ){
    System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}

Это покажет: 2

Другая реализация для count(), всего в одной строке:

public static int count(String string, String substr) {
    return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}

Ответ 6

Этот метод static возвращает количество вхождений строки в другую строку.

/**
 * Returns the number of appearances that a string have on another string.
 * 
 * @param source    a string to use as source of the match
 * @param sentence  a string that is a substring of source
 * @return the number of occurrences of sentence on source 
 */
public static int numberOfOccurrences(String source, String sentence) {
    int occurrences = 0;

    if (source.contains(sentence)) {
        int withSentenceLength    = source.length();
        int withoutSentenceLength = source.replace(sentence, "").length();
        occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
    }

    return occurrences;
}

Тесты:

String source = "Hello World!";
numberOfOccurrences(source, "Hello World!");   // 1
numberOfOccurrences(source, "ello W");         // 1
numberOfOccurrences(source, "l");              // 3
numberOfOccurrences(source, "fun");            // 0
numberOfOccurrences(source, "Hello");          // 1

Кстати, метод может быть написан в одной строке, ужасно, но он также работает:)

public static int numberOfOccurrences(String source, String sentence) {
    return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}

Ответ 7

версия Java 8.

System.out.println(Pattern.compile("\\bmale cat")
            .splitAsStream("i have a male cat. the color of male cat is Black")
            .count()-1);

Ответ 8

Почему не рекурсивный?

public class CatchTheMaleCat  {
    private static final String MALE_CAT = "male cat";
    static int count = 0;
    public static void main(String[] arg){
        wordCount("i have a male cat. the color of male cat is Black");
        System.out.println(count);
    }

    private static boolean wordCount(String str){
        if(str.contains(MALE_CAT)){
            count++;
            return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
        }
        else{
            return false;
        }
    }
}

Ответ 9

Это будет работать

int word_count(String text,String key){
   int count=0;
   while(text.contains(key)){
      count++;
      text=text.substring(text.indexOf(key)+key.length());
   }
   return count;
}

Ответ 10

открытый класс TestWordCount {

public static void main(String[] args) {

    int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
    System.out.println("count : "+count);

}

public static int numberOfOccurences(String findWord, String sentence) {

    int length = sentence.length();
    int lengthWithoutFindWord = sentence.replace(findWord, "").length();
    return (length - lengthWithoutFindWord)/findWord.length();

}

}

Ответ 11

Замените строку, которая должна быть подсчитана пустой строкой, а затем используйте длину без строки для вычисления числа вхождений.

public int occurrencesOf(String word)
    {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replace(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
    }

Ответ 12

Как только вы найдете этот термин, вам нужно удалить его из String в процессе, чтобы он не разрешил его снова, используйте indexOf() и substring(), вам не нужно делать, чтобы проверить длительность проверки

Ответ 13

Строка содержит эту строку все время, когда она проходит через нее. Вы не хотите, чтобы ++, потому что то, что это делает прямо сейчас, - это просто длина строки, если она содержит "мужскую кошку"

Вам нужно indexOf()/substring()

Как получить то, что я говорю?

Ответ 14

Если вы найдете строку, которую ищете, вы можете продолжить ее длину (если в случае, если вы ищете aa aaaa, вы считаете это 2 раза).

int c=0;
String found="male cat";
 for(int j=0; j<text.length();j++){
     if(text.contains(found)){
         c+=1;
         j+=found.length()-1;
     }
 }
 System.out.println("counter="+c);

Ответ 15

Это должно быть более быстрое решение без регулярных выражений.
(примечание - не Java-программист)

 String str = "i have a male cat. the color of male cat is Black";
 int found  = 0;
 int oldndx = 0;
 int newndx = 0;

 while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
 {
     found++;
     oldndx = newndx+8;
 }

Ответ 16

Существует так много способов для возникновения подстроки и двух тем: -

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

Ответ 17

Мы можем рассчитывать по многим причинам для возникновения подстроки: -

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

Ответ 18

У меня есть другой подход:

String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return 
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " + 
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());

Ответ 19

Здесь приведен полный пример,

package com.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WordsOccurances {

      public static void main(String[] args) {

            String sentence = "Java can run on many different operating "
                + "systems. This makes Java platform independent.";

            String[] words = sentence.split(" ");
            Map<String, Integer> wordsMap = new HashMap<String, Integer>();

            for (int i = 0; i<words.length; i++ ) {
                if (wordsMap.containsKey(words[i])) {
                    Integer value = wordsMap.get(words[i]);
                    wordsMap.put(words[i], value + 1);
                } else {
                    wordsMap.put(words[i], 1);
                }
            }

            /*Now iterate the HashMap to display the word with number 
           of time occurance            */

           Iterator it = wordsMap.entrySet().iterator();
           while (it.hasNext()) {
                Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
                System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
                                +entryKeyValue.getValue()+" times");
           }
     }
}

Ответ 20

открытый класс WordCount {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String scentence = "This is a treeis isis is is is";
    String word = "is";
    int wordCount = 0;
    for(int i =0;i<scentence.length();i++){
        if(word.charAt(0) == scentence.charAt(i)){
            if(i>0){
                if(scentence.charAt(i-1) == ' '){
                    if(i+word.length()<scentence.length()){
                        if(scentence.charAt(i+word.length()) != ' '){
                            continue;}
                        }
                    }
                else{
                    continue;
                }
            }
            int count = 1;
            for(int j=1 ; j<word.length();j++){
                i++;
                if(word.charAt(j) != scentence.charAt(i)){
                    break;
                }
                else{
                    count++;
                }
            }
            if(count == word.length()){
                wordCount++;
            }

        }
    }
    System.out.println("The word "+ word + " was repeated :" + wordCount);
}

}

Ответ 21

Простое решение - here-

Код ниже использует HashMap, поскольку он будет поддерживать ключи и значения. так что здесь ключи будут словом, а значения будут считаться (вхождение слова в заданной строке).

public class WordOccurance 
{

 public static void main(String[] args) 
 {
    HashMap<String, Integer> hm = new HashMap<>();
    String str = "avinash pande avinash pande avinash";

    //split the word with white space       
    String words[] = str.split(" ");
    for (String word : words) 
    {   
        //If already added/present in hashmap then increment the count by 1
        if(hm.containsKey(word))    
        {           
            hm.put(word, hm.get(word)+1);
        }
        else //if not added earlier then add with count 1
        {
            hm.put(word, 1);
        }

    }
    //Iterate over the hashmap
    Set<Entry<String, Integer>> entry =  hm.entrySet();
    for (Entry<String, Integer> entry2 : entry) 
    {
        System.out.println(entry2.getKey() + "      "+entry2.getValue());
    }
}

}

Ответ 22

public int occurrencesOf(String word) {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replaceAll(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
}