查找字符串中的重复单词的Java程序
1 说明
在此程序中,我们需要找出字符串中存在的重复单词并显示这些单词。
示例:
big black bug bit a big black dog on his big black nose
为了从字符串中找到重复的单词,我们首先将字符串拆分为单词。我们计算字符串中每个单词的出现次数。如果count大于1,则表示单词在字符串中重复。
2 算法思路
- 步骤1:开始
- 步骤2: 定义String string = "Big black bug bit a big black dog on his big black nose"
- 步骤3:定义计数
- 步骤4:将字符串转换为小写字母。
- 第5步:初始化words []以分割字符串。
- 步骤6:打印“Duplicate words in a given string:”
- 步骤7: SET i = 0。重复步骤8至12,直到i
- 步骤8: SET计数= 1。
- 步骤9: SET j = i + 1。直到j将步骤10重复到步骤11
- 步骤10: IF(words [i] .equals(words [j])
然后
count = count + 1个
单词[j] = 0 - 步骤11: j = j + 1
- 步骤12: i = i + 1
- 步骤13:如果先先计算IF(count> 1 && words [i]!= 0),然后再打印word [i]
- 步骤13:结束
3 程序实现
/**
* 一点教程网: http://www.yiidian.com
*/
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
热门文章
优秀文章