- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to find all duplicate characters in a string
The duplicate characters in a string are those that occur more than once. These characters can be found using a nested for loop. An example of this is given as follows −
String = Apple
In the above string, p is a duplicate character as it occurs more than once.
A program that demonstrates this is given as follows.
Example
public class Example { public static void main(String argu[]) { String str = "beautiful beach"; char[] carray = str.toCharArray(); System.out.println("The string is:" + str); System.out.print("Duplicate Characters in above string are: "); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (carray[i] == carray[j]) { System.out.print(carray[j] + " "); break; } } } } }
Output
The string is:beautiful beach Duplicate Characters in above string are: b e a u
Now let us understand the above program.
First, the string str is defined. Then, str.toCharArray() converts the string into a sequence of characters. The original string is displayed. The code snippet that demonstrates this is given as follows −
String str = "beautiful beach"; char[] carray = str.toCharArray(); System.out.println("The string is:" + str);
The duplicate characters are found in the string using a nested for loop. Then these characters are displayed. The code snippet that demonstrates this is given as follows.
System.out.print("Duplicate Characters in above string are: "); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (carray[i] == carray[j]) { System.out.print(carray[j] + " "); break; } } }
Advertisements