Home > database >  How do I prevent recurrence Strings?
How do I prevent recurrence Strings?

Time:11-04

I've defines a function printWordsOccurence(String str). it's job to print How many times is each word repeated in this text :

Text: I am happy. I am a doctor. I like chocolate.

the expected results :

  1. [3] I
  2. [2] am
  3. [1] happy.
  4. [1] a
  5. [1] doctor.
  6. [1] like
  7. [1] chocolate.

Here is my code :

 public static void printWordsOccurence(String str) {

    String[] words = str.split(" ");
    int counter = 0;

    for (int i = 0; i < words.length; i  ) {
        for (int j = 0; j < words.length; j  ) {
            if (words[i].equals(words[j])) {
                counter  ;
            }
        }
        System.out.println(counter   " "   words[i]);
        counter=0;
    }
}

I can't prevent strings from repeating. Any suggestions or hint would be very helpful

CodePudding user response:

What you need to do is to not process words you have already seen. So when the outer loop sees a familiar one it needs to skip it.

The easiest way do do this would be to use a set or a map. But there is another alternative using most of your existing code.

  • simply replace the word when it is encountered with some string.
  • then if that string is encountered again by the outer loop, ignore it.
public static void printWordsOccurence(String str) {
    
    String[] words = str.split(" ");
    // the marker which replaces the word when found.
    String seen = "#";

    for (int i = 0; i < words.length; i  ) {
        
        // if the word equals the marker, continue continue on
        // to the next word in this loop
        if (words[i].equals(seen)) {
            continue;
        }

        int counter = 0;

        // save the word since it may change when found
        String find = words[i];

        for (int j = 0; j < words.length; j  ) {
            if (find.equals(words[j])) {
                // replace the word with the substitute
                words[j] = seen;
                counter  ;
            }
        }
        
        System.out.println(counter   " "   find);
    }
}

prints

3 I
2 am
1 happy.
1 a
1 doctor.
1 like
1 chocolate.

You may want to modify the words to eliminate any lingering punctuation.

CodePudding user response:

You are printing the message within the outer loop and it will get executed for each of the words! Please try to use Map. Here I don't use the stream. Just used Java 7 way. `

public static void printWordsOccurence(String str) {

        String[] words = str.split(" ");

        Map<String, Integer> res = new LinkedHashMap<>();

        for (String w : words) {
            if (res.containsKey(w)) {
                res.put(w, res.get(w)   1);
            } else {
                res.put(w, 1);
            }
        }

        for (String w: res.keySet()) {
            System.out.println("["   res.get(w)   "]"   w);
        }
    }

`

CodePudding user response:

private static void printWordOccurance(String sentence) {
    Map<String, Integer> countMap = new HashMap<>();
    Arrays.stream(sentence.split("\\s ")).forEach(word -> countMap.compute(word, (k, v) -> v == null ? 1 : v   1));
        
    System.out.println(countMap);
}

CodePudding user response:

    using [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html][1]

        String str= "I am happy. I am a doctor. I like chocolate.";
        str= str.replace(".", "");

        String[] words = str.split(" ");
        Map<String, Integer> counter = new HashMap<>();

        for (String w: words) {
            if(counter.containsKey(w)){
                counter.replace(w, counter.get(w) 1);
            }else{
                counter.put(w,1);
            }
        }
        System.out.println(counter.toString());

CodePudding user response:

Try this.

public static void printWordsOccurence(String str) {
    Arrays.stream(str.split("[\\s.] "))
        .collect(Collectors.groupingBy(Function.identity(),
            LinkedHashMap::new, Collectors.counting()))
        .entrySet().forEach(e ->
            System.out.println("["   e.getValue()   "] "   e.getKey()));
}

public static void main(String[] args) {
    String str = "I am happy. I am a doctor. I like chocolate.";
    printWordsOccurence(str);
}

output:

[3] I
[2] am
[1] happy
[1] a
[1] doctor
[1] like
[1] chocolate

Or

public static void printWordsOccurence(String str) {
    Map<String, Integer> counter = new LinkedHashMap<>();
    for (String word : str.split("[\\s.] "))
        counter.merge(word, 1, Integer::sum);
    for (Entry<String, Integer> e : counter.entrySet())
        System.out.println("["   e.getValue()   "] "   e.getKey());
}
  • Related