public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
// breaking in to characters
char[] str1 = s1.toCharArray();
System.out.println("Duplicate are :");
//creating outer loop for string length
for (int i = 0; i < s1.length(); i++) {
//creating inner loop for comparison
for (int j = i + 1; j < s1.length(); j++) {
//comparing value of i and j
if (str1[i] == str1[j]) {
System.out.println(str1[j]);
System.out.println(count);
//increment after comparison
count++;
break;
}
}
}
sc.close();
}
输出:
aassdesdd
Duplicate are :
a
s
s
d
d
答案 0 :(得分:1)
如果您只想打印连续的重复项(即输入“ aassdesdd”,输出asd而不是assdd),则可以将内部循环与相等性检查结合使用:
for(int i = 0; i < s1.length(); i++) {
for(int j = i + 1; j < s1.length() && str1[i] == str1[j]; j++) {
System.out.println(str1[j]);
}
}
答案 1 :(得分:0)
如果您只想打印连续的不同字符,则只有一个循环,并且每次迭代都可以检查当前字符和下一个字符。如果它们相同,则打印。为了避免再次打印相同的字符,我们可以设置标志。这可以使用单循环来实现
char[] str1 = "aasssdesdd".toCharArray();
boolean flag=true;
for(int i = 0; i < str1.length-1; i++) {
if (flag && str1[i]==str1[i+1])
{
System.out.println(str1[i]);
// we found duplicate, mark the flag as false
flag=false;
continue;
}
flag = true;
}
输出:
a
s
d