Java String Exercises: Count and print all the duplicates in the input string
Java String: Exercise-51 with Solution
Write a Java program to count and print all the duplicates in the input string.
Sample Solution:
Java Code:
import java.util.*;
public class Main
{
static final int MAX_CHARS = 256;
static void CountCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
static void showDuplicates(String str1)
{
int ctr[] = new int[MAX_CHARS];
CountCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++)
if(ctr[i] > 1)
System.out.printf("%c appears %d times\n", i, ctr[i]);
}
public static void main(String[] args)
{
String str1 = "w3resource";
System.out.println("The given string is: "+str1);
System.out.println("The duplicate characters and counts are: ");
showDuplicates(str1);
}
}
Sample Output:
The given string is: w3resource The duplicate characters and counts are: e appears 2 times r appears 2 times
Pictorial Presentation:
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to find lexicographic rank of a given string.
Next: Write a Java program to check if two given strings are rotations of each other.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework