简体   繁体   中英

How do i ignore same words in a string (JAVA)

I want to find how many words there are in a string but ignore the similar words in it.

For example the main method should return 8 insetad 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 HashMaps, ArrayLists, only charAt, length, or substring and using loops and if statemens are allowed .

public static void main(String[] args) {

countUniqueWords("A long long time ago, I can still remember");

public static int countUniqueWords(String str) {
    char[] sentence = str.toCharArray();
    boolean inWord = false;
    int wordCt = 0;
    for (char c : sentence) {
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
            if (!inWord) {
                wordCt++;
                inWord = true;
            }
        } else {
            inWord = false;
        }
    }
    return wordCt;
}
```

Don't force yourself to limited options, and learn the Streaming API. Your question is as simple as:

public static long countUniqueWords(String str) {
    var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" +", " ");
    return Arrays.stream(str2.split(" "))
            .distinct()
            .count();
}
  1. [Optional step] Get get rid of all non alphanumeric chars
  2. Split the string per empty slot
  3. Remove duplicates
  4. Add them together

Try this:

public static int countUniqueWords(String words) {
    // Add all the words to a list
    List<String> array = new ArrayList<>();
    Scanner in = new Scanner(words);
    while (in.hasNext()) {
        String s = in.next();
        array.add(s);
    }

    // Save per word the amount of duplicates
    HashMap<String, Integer> listOfWords = new HashMap<>();
    Iterator<String> itr = array.iterator();
    while (itr.hasNext()) {
        String next = itr.next();
        String prev = listOfWords.getOrDefault(next, 0);
        listOfWords.put(next, prev + 1);
    }

    // Grab the size of all known words
    return listOfWords.size();
}

public static void main(String args[]) { 
    int count = countUniqueWords("A long long time ago, I can still remember");
    System.out.println("The number of unique words: " + count);
}

To ignore same words in a string, you can use a combination of the split and distinct methods from the Java Stream API.

    // Define the input string
String input = "This is a test string with some repeating words";

// Split the string into an array of words
String[] words = input.split("\\s+");

// Use the distinct method to remove duplicate words from the array
String[] distinctWords = Arrays.stream(words).distinct().toArray(String[]::new);

// Print the distinct words
System.out.println(Arrays.toString(distinctWords));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM