Finding repeated words on a string and counting the repetitions

后端 未结 29 878
梦谈多话
梦谈多话 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<E>
    {
        public static void main(String[] args) 
        {
            Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
            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<Integer> value = new ArrayList<Integer>(unique.values());
    
            System.out.println("Output = " + uniqueString);
            System.out.println("Values = " + value);
    
        }
    
        public static String join(Collection<String> s, String delimiter) {
            StringBuffer buffer = new StringBuffer();
            Iterator<String> 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.

    0 讨论(0)
  • 2021-02-05 18:11
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    
    public class CountRepeatedWords {
    
        public static void main(String[] args) {
              countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.");
        }
    
        public static void countRepeatedWords(String wordToFind) {
            String[] words = wordToFind.split(" ");
            HashMap<String, Integer> wordMap = new LinkedHashMap<String, Integer>();
    
            for (String word : words) {
                wordMap.put(word,
                    (wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1)));
            }
    
                System.out.println(wordMap);
        }
    
    }
    
    0 讨论(0)
  • 2021-02-05 18:14

    If this is a homework, then all I can say is: use String.split() and HashMap<String,Integer>.

    (I see you've found split() already. You're along the right lines then.)

    0 讨论(0)
  • 2021-02-05 18:14

    Using Java 8 streams collectors:

    public static Map<String, Integer> countRepetitions(String str) {
        return Arrays.stream(str.split(", "))
            .collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a + 1));
    }
    

    Input: "House, House, House, Dog, Dog, Dog, Dog, Cat"

    Output: {Cat=1, House=3, Dog=4}

    0 讨论(0)
  • 2021-02-05 18:14

    Use Function.identity() inside Collectors.groupingBy and store everything in a MAP.

    String a  = "Gini Gina Gina Gina Gina Protijayi Protijayi "; 
            Map<String, Long> map11 = Arrays.stream(a.split(" ")).collect(Collectors
                    .groupingBy(Function.identity(),Collectors.counting()));
            System.out.println(map11);
    
    // output => {Gina=4, Gini=1, Protijayi=2}
    

    In Python we can use collections.Counter()

    a = "Roopa Roopi  loves green color Roopa Roopi"
    words = a.split()
    
    wordsCount = collections.Counter(words)
    for word,count in sorted(wordsCount.items()):
        print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" ))
    

    Output :

    "Roopa" is repeated 2 times. "Roopi" is repeated 2 times. "color" is repeated 1 time. "green" is repeated 1 time. "loves" is repeated 1 time.

    0 讨论(0)
  • 2021-02-05 18:15

    Hope this helps :

    public static int countOfStringInAText(String stringToBeSearched, String masterString){
    
        int count = 0;
        while (masterString.indexOf(stringToBeSearched)>=0){
          count = count + 1;
          masterString = masterString.substring(masterString.indexOf(stringToBeSearched)+1);
        }
        return count;
    }
    
    0 讨论(0)
提交回复
热议问题