Java在字符串中查找重复的单词
在此程序中,我们需要找出字符串中存在的重复单词并显示这些单词。
示例: 大黑虫咬住了大黑狗的大黑鼻子
要从字符串中查找重复的单词,我们首先将字符串拆分为单词。我们计算字符串中每个单词的出现。如果count大于1,则表示字符串中的单词是重复的。
ALGORITHM
步骤1: START
第2步: DEFINE字符串string ="Big black bug bit a big black dog on his big black nose"
步骤3: 定义 count
步骤4: 将字符串转换为小写字母。
步骤5: 初始化words[]以分割字符串。
步骤6: 打印"Duplicate words in a given string: "
步骤7: SET i = 0。重复步骤8至12
步骤8: SET count = 1。
步骤9: SET j = i + 1。直到j将步骤10重复到步骤11
步骤10: IF(words[i].equals(words[j])
然后
count = count + 1
words[j] = 0
步骤11: j = j + 1
步骤12: i = i + 1
步骤13: IF(count> 1 && words[i]!= 0) 然后 打印words[i]
步骤13: END
程序:
public class DuplicateWord {
public static void main(String[] args) {
String string = "Big black bug bit a big black dog on his big black nose";
int count;
//Converts the string into lowercase
string = string.toLowerCase();
//Split the string into words using built-in function
String words[] = string.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
//Set words[j] to 0 to avoid printing visited word
words[j] = "0";
}
}
//Displays the duplicate word if count is greater than 1
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
输出:
Duplicate words in a given string :
big
black