我想找出一个字符串中有多少个单词,但忽略其中相似的单词。
例如,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;
}
不要强迫自己选择有限的选项,学习 Streaming API。你的问题很简单:
public static long countUniqueWords(String str) {
var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" +", " ");
return Arrays.stream(str2.split(" "))
.distinct()
.count();
}
要忽略字符串中的相同单词,您可以结合使用 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));
试试这个:
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);
}
我让它工作了,但不确定它的可扩展性。
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
。