Home > Enterprise >  How do i count how many words there are, and ignore same words in a string? (using method)
How do i count how many words there are, and ignore same words in a string? (using method)

Time:12-04

The code here only shows how many words they are, how do i ignore the words that are the same? For example, "A long long time ago, I can still remember", would return 8 instead of 9.

I want it to be a method which takes one parameter s of type String and returns an int value. And im only allowed to use the bacics, so no hash keys and advance stuff.

  public static int mostCommonLetter(String s){

                    int wordCount = 0;

                    boolean word = false;
                    int endOfLine = s.length() - 1;

                    for (int i = 0; i < s.length(); i  ) {
                       
                        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
                            word = true;
                          
                        } else if (!Character.isLetter(s.charAt(i)) && word) {
                            wordCount  ;
                            word = false;
                          
                        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
                            wordCount  ;
                        }
                    }
                    return wordCount;
                }
} 
        

How do i ignore the words that are the same?

CodePudding user response:

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
      String input = "A long long time ago, I can still remember";
      String[] words = input.split(" ");
      List<String> uniqueWords = new ArrayList<>();
      for (String word : words) {
        if (!uniqueWords.contains(word)) {
            uniqueWords.add(word);
        }      
      }
      System.out.println("Number of unique words: "   uniqueWords.size());
    }
}

Output: Number of unique words: 8

Basically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.

CodePudding user response:

General idea:

public Set<String> getUniqueWords(String input) {
    // Split the string into words using the split() method
    String[] words = input.split(" ");

    // Create a Set to store the unique words
    Set<String> uniqueWords = new HashSet<String>();

    // Loop through the words and add them to the Set
    for (String word : words) {
        uniqueWords.add(word);
    }

    // Return the Set of unique words
    return uniqueWords;
}

Same solution using StreamAPI:

public Set<String> getUniqueWords(String input) {
    return Arrays.stream(input.split(" ")).collect(Collectors.toUnmodifiableSet());
}

// or

public List<String> getUniqueWords2(String input) {
    return Arrays.stream(input.split(" ")).distinct().toList();
}

If it is needed to handle multiple spaces between words, add some cleanup for input:

// remove leading and trailing spaces
cleanInput = input.trim();

// replace multiple spaces with a single space
cleanInput = cleanInput.replaceAll("\\s ", " "); 
  • Related