In this program, we need to find out the duplicate words present in the string and display those words.
IMPLEMENTATION:
1. Lets start with creating class and main class under it.
public class DuplicateCharacters
{
public static void main(String[] args)
{
2. Now define String using auto generated method and also define integer count and initialize it with zero.
String str = new String("Programmers door");
int count=0;
3. After this lets create a character array to convert our string variable to the character.
char[] chars=str.toCharArray();
4.Now lets create for loops for comparing characters and if two characters of consecutive index match, then we will print that character and the counter will be incremented by 1 after each iteration.
System.out.println("Duplicate characters are:");
for (int i=0; i<str.length();i++)
{
for(int j=i+1; j<str.length();j++)
{
if (chars[i] == chars[j])
{
System.out.println(chars[j]);
count++;
break;
}
}
}
}
OUTPUT:
Duplicate characters are:
r
o
r
m
r
o
Happy Coding!
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
Follow Programmers Door for more.
留言