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

xtfmy6hx  于 2022-12-10  发布在  Java
关注(0)|答案(3)|浏览(115)

我想找出一个字符串中有多少个单词,但忽略其中相似的单词。
例如,main方法应返回9的8 insetad。
我希望它是一个方法,接受一个字符串类型的参数,返回一个整型值,我只允许使用bacics,所以不能使用HashMaps,ArrayLists,只能使用charAt,length,或者substring,使用循环和if语句.

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

carvr3hs1#

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

public static long countUniqueWords(String str) {
    var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" +", " ");
    return Arrays.stream(str2.split(" "))
            .distinct()
            .count();
}

1.[可选步骤] 删除所有非字母数字字符
1.按空插槽拆分字符串
1.删除重复项
1.将它们加在一起

nbysray5

nbysray52#

要忽略字符串中的相同单词,可以组合使用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));
jhkqcmku

jhkqcmku3#

试试这个:

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

相关问题