Finding repeated words on a string and counting the repetitions

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

    package day2;
    
    import java.util.ArrayList;
    import java.util.HashMap;`enter code here`
    import java.util.List;
    
    public class DuplicateWords {
    
        public static void main(String[] args) {
            String S1 = "House, House, House, Dog, Dog, Dog, Dog";
            String S2 = S1.toLowerCase();
            String[] S3 = S2.split("\\s");
    
            List a1 = new ArrayList();
            HashMap hm = new HashMap<>();
    
            for (int i = 0; i < S3.length - 1; i++) {
    
                if(!a1.contains(S3[i]))
                {
                    a1.add(S3[i]);
                }
                else
                {
                    continue;
                }
    
                int Count = 0;
    
                for (int j = 0; j < S3.length - 1; j++)
                {
                    if(S3[j].equals(S3[i]))
                    {
                        Count++;
                    }
                }
    
                hm.put(S3[i], Count);
            }
    
            System.out.println("Duplicate Words and their number of occurrences in String S1 : " + hm);
        }
    }
    

提交回复
热议问题