I'm new here and still learning. Today I learn find duplicate in string. From https://www.javatpoint.com/program-to-find-the-duplicate-characters-in-a-string, I try to learn complete code from web.
When string = "Great responsibility" the output will be:
Duplicate characters in a given string:
r
e
t
s
i
because it has duplicate character r e t s i
And when string is "great" the output is
Duplicate characters in a given string:
The output is blank because there are no duplicate characters, so I give a description "no duplicate" to define no character duplicate and the output goes like this
Duplicate characters in a given string:
no duplicates
no duplicates
no duplicates
no duplicates
no duplicates
This returns too many descriptions.
My code
public class DuplicateCharacters {
public static void main(String[] args) {
String string1 = "Great";
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]);
else
System.out.println("no duplicates");
}
}
}
How can I print only one description without repetition? I tried return 0; but it does not work.
Expected output
Duplicate characters in a given string:
no duplicates