Finding repeated words on a string and counting the repetitions

后端 未结 29 892
梦谈多话
梦谈多话 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:24

    Please use the below code. It is the most simplest as per my analysis. Hope you will like it:

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Scanner;
    import java.util.Set;
    
    public class MostRepeatingWord {
    
        String mostRepeatedWord(String s){
            String[] splitted = s.split(" ");
            List listString = Arrays.asList(splitted);
            Set setString = new HashSet(listString);
            int count = 0;
            int maxCount = 1;
            String maxRepeated = null;
            for(String inp: setString){
                count = Collections.frequency(listString, inp);
                if(count > maxCount){
                    maxCount = count;
                    maxRepeated = inp;
                }
            }
            return maxRepeated;
        }
        public static void main(String[] args) 
        {       
            System.out.println("Enter The Sentence: ");
            Scanner s = new Scanner(System.in);
            String input = s.nextLine();
            MostRepeatingWord mrw = new MostRepeatingWord();
            System.out.println("Most repeated word is: " + mrw.mostRepeatedWord(input));
    
        }
    }
    

提交回复
热议问题