Finding repeated words on a string and counting the repetitions

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

    As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.

    import java.util.*;
    
    public class Genric
    {
        public static void main(String[] args) 
        {
            Map unique = new LinkedHashMap();
            for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
                if(unique.get(string) == null)
                    unique.put(string, 1);
                else
                    unique.put(string, unique.get(string) + 1);
            }
            String uniqueString = join(unique.keySet(), ", ");
            List value = new ArrayList(unique.values());
    
            System.out.println("Output = " + uniqueString);
            System.out.println("Values = " + value);
    
        }
    
        public static String join(Collection s, String delimiter) {
            StringBuffer buffer = new StringBuffer();
            Iterator iter = s.iterator();
            while (iter.hasNext()) {
                buffer.append(iter.next());
                if (iter.hasNext()) {
                    buffer.append(delimiter);
                }
            }
            return buffer.toString();
        }
    }
    

    New String is Output = House, Dog

    Int array (or rather list) Values = [3, 4] (you can use List::toArray) for getting an array.

提交回复
热议问题