簡體   English   中英

我如何忽略字符串中的相同單詞(JAVA)

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

我想找出一個字符串中有多少個單詞,但忽略其中相似的單詞。

例如,main 方法應該返回 8 insetad of 9。

我希望它是一種方法,它接受一個 String 類型的參數並返回一個 int 值。 而且我只允許使用基本知識,所以沒有 HashMaps、ArrayLists,只有 charAt、length 或 substring 並使用循環和 if statemens 是允許的

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

不要強迫自己選擇有限的選項,學習 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. 將它們加在一起

試試這個:

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

要忽略字符串中的相同單詞,可以結合使用 Java Stream API 中的 split 和 distinct 方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM