Answers for "count how many words in a string c"

0

how to count words in string

String str = "I am happy and why not
  and why are you not happy and you should be";
        String [] arr = str.split(" ");
        Map<String, Integer> map = new HashMap<>();

        for (int i=0 ; i < arr.length ; i++){
                if (!map.containsKey(arr[i])){
                    map.put(arr[i],1);
                } else{
                    map.put(arr[i],map.get(arr[i])+1);
                }
        }
        for(Map.Entry<String, Integer> each : map.entrySet()){

  System.out.println(each.getKey()+" occures " + each.getValue() + " times");
        }
Posted by: Guest on January-22-2021
0

program code for counting the similarwrod in the sentences

public static int count(String word) {
    if (word == null || word.isEmpty()) {
      return 0;
    }

    int wordCount = 0;

    boolean isWord = false;
    int endOfLine = word.length() - 1;
    char[] characters = word.toCharArray();

    for (int i = 0; i < characters.length; i++) {

      // if the char is a letter, word = true.
      if (Character.isLetter(characters[i]) && i != endOfLine) {
        isWord = true;

        // if char isn't a letter and there have been letters before,
        // counter goes up.
      } else if (!Character.isLetter(characters[i]) && isWord) {
        wordCount++;
        isWord = false;

        // last word of String; if it doesn't end with a non letter, it
        // wouldn't count without this.
      } else if (Character.isLetter(characters[i]) && i == endOfLine) {
        wordCount++;
      }
    }

    return wordCount;
  }
Posted by: Guest on October-31-2020

Code answers related to "count how many words in a string c"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language