http://www.technicalpage.net/search/label/SQL

Count words in a Sentence or Count characters in a given word or string

 

package testing;

 

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

 

public class CountWordsCharsUsingHashmap {

 

     public static void main(String[] args) {

         wordCountInSentence();

         countCharsInGivenWord();

     }

        

     //word count in a sentence using Hashmap

         public static void wordCountInSentence() {

        

         String word = "this is a beautiful a this a is yes beautiful";

         Map<String, Integer> map = new HashMap<String, Integer>();

        

         String[] str = word.split(" ");

         int count = 0;

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

              String wordAti = str[i];

              if((map.containsKey(wordAti))  ) {

                  map.put(wordAti, (map.get(wordAti))+1);

              }else {

                  map.put(wordAti, 1);

              }

         }

         System.out.println("count of words : "+map);

     }

 //------------------------------------------------------------

     //char count in a word/string using Hashmap

     public static void countCharsInGivenWord() {   

     String word1 = "asdfdefaefdea";

    

     Map<String, Integer> map = new HashMap<>();

     int len = word1.length();

     int mapKeyCount=0 ;

     for(int i=0;i<len;i++) {

         String charAti = Character.toString(word1.charAt(i));

         if(map.containsKey(charAti)) {

              mapKeyCount =map.get(charAti)+1;

         } else {

              mapKeyCount =1;

         }

         map.put(charAti, mapKeyCount);

     }

     System.out.println("count of characters: "+map);

     }

}

 

Output:

count of words : {a=3, beautiful=2, yes=1, this=2, is=2}

count of characters: {a=3, s=1, d=3, e=3, f=3}

No comments:

Post a Comment