Finding repeated words on a string and counting the repetitions

后端 未结 29 1385
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  离开以前
    2021-02-05 18:23

    //program to find number of repeating characters in a string
    //Developed by Rahul Lakhmara
    
    import java.util.*;
    
    public class CountWordsInString {
        public static void main(String[] args) {
            String original = "I am rahul am i sunil so i can say am i";
            // making String type of array
            String[] originalSplit = original.split(" ");
            // if word has only one occurrence
            int count = 1;
            // LinkedHashMap will store the word as key and number of occurrence as
            // value
            Map wordMap = new LinkedHashMap();
    
            for (int i = 0; i < originalSplit.length - 1; i++) {
                for (int j = i + 1; j < originalSplit.length; j++) {
                    if (originalSplit[i].equals(originalSplit[j])) {
                        // Increment in count, it will count how many time word
                        // occurred
                        count++;
                    }
                }
                // if word is already present so we will not add in Map
                if (wordMap.containsKey(originalSplit[i])) {
                    count = 1;
                } else {
                    wordMap.put(originalSplit[i], count);
                    count = 1;
                }
            }
    
            Set word = wordMap.entrySet();
            Iterator itr = word.iterator();
            while (itr.hasNext()) {
                Map.Entry map = (Map.Entry) itr.next();
                // Printing
                System.out.println(map.getKey() + " " + map.getValue());
            }
        }
    }
    

提交回复
热议问题