如何忽略字符串中的相同单词(Java)?

问题描述 投票:0回答:4

我想找出一个字符串中有多少个单词,但忽略其中相似的单词。

例如,main方法应该返回8而不是9。

我希望它是一种方法,它接受一个 String 类型的参数并返回一个 int 值。而且我只被允许使用基础知识,因此 HashMap、ArrayList、循环和 if 语句是不允许的。只允许使用 charAt、length 和 substring。

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;
}
java string char return
4个回答
3
投票

不要强迫自己选择有限的选项,学习 Streaming API。你的问题很简单:

public static long countUniqueWords(String str) {
    var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" +", " ");
    return Arrays.stream(str2.split(" "))
            .distinct()
            .count();
}
  1. [可选步骤] 删除所有非字母数字字符
  2. 将字符串拆分为每个空槽
  3. 删除重复项
  4. 将它们加在一起

0
投票

要忽略字符串中的相同单词,您可以结合使用 Java Stream API 中的 split 和 unique 方法。

    // 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));

0
投票

试试这个:

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);
}

0
投票

我让它工作了,但不确定它的可扩展性。

int countUniqueWords(String str) {
    String set = "";
    boolean found;
    for (String wordA : str.split("\\s+")) {
        if (set.isEmpty())
            set = wordA;
        else {
            found = false;
            for (String wordB : set.split("\\s+")) {
                if (wordB.equalsIgnoreCase(wordA)) {
                    found = true;
                    break;
                }
            }
            if (!found) set += " " + wordA;
        }
    }
    return set.split(" ").length;
}

理想情况下,您希望使用

Pattern
Matcher
,这样您就可以使用字边界和字捕获,
\b([\w&&[^\d]]+)\b

这将删除任何可能包含数字的单词,并消除任何孤立的标点符号的计数。

© www.soinside.com 2019 - 2024. All rights reserved.