我应该创建一个方法来计算句子中满足或超过 int minLength 的单词数。例如,如果给定的最小长度为 4,则您的程序应该只计算长度至少为 4 个字母的单词。
单词 can 将由一个或多个空格分隔。可能存在非字母字符(空格、标点符号、数字等),但它们不计入单词的长度。
public static int countWords(String original, int minLength) {
original = original.replaceAll("[^A-Za-z\\s]", "").replaceAll("[0-9]", "");
String[] words = original.split("\\s+");
for(String word : words){ System.out.println(word); }
int count = 0;
for (int i = 0; i < words.length; i++) {
if (words[i].length() >= minLength) {
count++;
} else if (words[i].length() < minLength || minLength == 0) {
count = 0;
}
}
System.out.println("Number of words in sentence: " + count);
return count;
}
好的,我更改了代码,但计数器现在减少了 1。假设我输入以下内容:西类牙是一个美丽的国家;海滩温暖、沙质丰富、一尘不染。”
我收到的输出是... 西类牙 是 A 美丽的 国家 这 海滩 是 温暖的 沙 和 一尘不染 干净的 句子字数:10
单词数少了一个,应该是11。看起来它没有计算句子中的最后一个单词。我不确定问题出在哪里,考虑到我只更改了 ReplaceAll 以包含转义字符。
最佳答案
您得到的结果不正确,因为在 else if 条件内,计数更新为 0。 因此,一旦出现长度 < minLength 的单词,您的计数器就会重置。 您可以删除 else if 条件,这应该可以修复您的代码。
此外,以下是编写相同代码的另外 2 个选项,并提供所需的注释以了解每个步骤发生的情况。
选项 1:
private static long countWords(final String sentence, final int minLength) {
// Validate the input sentence is not null or empty.
if (sentence == null || sentence.isEmpty()) {
return 0;
}
long count = 0;
// split the sentence by spaces to get array of words.
final String[] words = sentence.split(" ");
for (final String word : words) { // for each word
// remove unwanted characters from the word.
final String normalizedWord = word.trim().replaceAll("[^a-zA-Z0-9]", "");
// if the length of word is greater than or equal to minLength provided, increment the counter.
if (normalizedWord.length() >= minLength) {
count++;
}
}
return count;
}
选项 2:[使用 Java 8 流]
private static long countWords(final String sentence, final int minLength) {
// Validate the input sentence is not null or empty.
if (sentence == null || sentence.isEmpty()) {
return 0;
}
return Stream.of(sentence.split(" "))
.filter(word -> word.trim().replaceAll("[^a-zA-Z0-9]", "").length() >= minLength)
.count();
}
对于输入字符串:“西类牙是一个美丽的国家;海滩温暖、沙滩多且一尘不染。”
Min Length: 3. Output: 11 Min Length: 4. Output: 8 Min Length: 5. Output: 7
对于输入字符串:“这就像魔术一样!”
Min Length: 4. Output: 5 Min Length: 5. Output: 2 Min Length: 6. Output: 0
对于输入字符串:“hello$hello”
Min Length: 4. Output: 1 Min Length: 5. Output: 1 Min Length: 6. Output: 1
关于java - 计算字符串中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499752/