查找字符串中的重复字符的Java程序
1 说明
在此程序中,我们需要在字符串中查找重复的字符。
Great responsibility
为了从字符串中找到重复的字符,我们对字符串中每个字符的出现进行计数。如果count大于1,则表示字符在字符串中具有重复的条目。在上面的示例中,以绿色突出显示的字符是重复字符。
2 算法思路
- 步骤1:开始
- 步骤2: 定义字符串string1 =“Great responsibility”
- 步骤3:定义计数
- 步骤4:将string1转换为char string []。
- 步骤5:打印“在给定的字符串中重复字符:”
- 步骤6: SET i =0。直到i重复步骤7至步骤11
- 步骤7: SET计数= 1
- 步骤8: SET j = i + 1。直到j将步骤8重复到步骤10
- 步骤9: IF(string [i] == string [j] && string [i]!='')
然后
count = count + 1
string [j] = 0 - 步骤10: j = j + 1
- 步骤11: i = i + 1
- 步骤12: IF(count> 1 && string [i]!= 0)然后PRINT string [i]
- 步骤13:结束
3 程序实现
/**
* 一点教程网: http://www.yiidian.com
*/
public class DuplicateCharacters {
public static void main(String[] args) {
String string1 = "Great responsibility";
int count;
//Converts given string into character array
char string[] = string1.toCharArray();
System.out.println("Duplicate characters in a given string: ");
//Counts each character present in the string
for(int i = 0; i <string.length; i++) {
count = 1;
for(int j = i+1; j <string.length; j++) {
if(string[i] == string[j] && string[i] != ' ') {
count++;
//Set string[j] to 0 to avoid printing visited character
string[j] = '0';
}
}
//A character is considered as duplicate if count is greater than 1
if(count > 1 && string[i] != '0')
System.out.println(string[i]);
}
}
}
以上代码输出结果为:
Duplicate characters in a given string:
r
e
t
s
i
热门文章
优秀文章