Reputation: 83
I need to get the count of each repeated characters separately....I have tried..but it returns only the count of unique count of characters...
Input :
SSDDVVDSSS
output :
S - 5
D - 3
V - 2
here is my code
public class q2 {
public static void main(String[] args) {
System.out.println(countUniqueCharacters("SSDDVVDSSS"));
}
public static int countUniqueCharacters(String input) {
boolean[] isItThere = new boolean[Character.MAX_VALUE];
for (int i = 0; i < input.length(); i++) {
isItThere[input.charAt(i)] = true;
}
int count = 0;
for (int i = 0; i < isItThere.length; i++) {
if (isItThere[i] == true){
count++;
}
}
return count;
}
}
Upvotes: 1
Views: 594
Reputation: 37073
Following are the issues in your code:
There are multiple ways in which you could solve this problem:
Using int array with index from 0 - 26 that maintains count of character A-Z and finally you print the count:
public static void main(String[] args) {
int[] counts = countUniqueCharacters("SSDDVVDSSS");
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println("char " + ((char) ('A' + i)) + " repeated " + counts[i] + " times");
}
}
}
public static int[] countUniqueCharacters(String input) {
int[] counts = new int[26];
for (int i = 0; i < input.length(); i++) {
counts[input.charAt(i) - 'A']++;
}
return counts;
}
Another way is to use map with character as key and int as value which would represent the count of that character repeatation.
Upvotes: 1
Reputation: 2378
Your last 'for' loop goes over the counter array and count how much entries with true value it contains. Therefore you get number of unique chars.
Try this:
public class q2 {
public static void main(String[] args) {
countUniqueCharacters("SSDDVVDSSS");
}
public static void countUniqueCharacters(String input) {
Map<Character,Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < input.length(); i++){
if (map.get(input.charAt(i)) == null){
map.put(input.charAt(i),1);
}
else{
map.put(input.charAt(i),map.get(input.charAt(i))+1);
}
}
System.out.print(map);
}
}
Upvotes: 0
Reputation: 2934
public static void main(String[] args) {
String str = "SSDDVVDSSS";
int counts[] = new int[(int) Character.MAX_VALUE];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
counts[(int) c]++;
}
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.print((char) i + "-" + counts[i] + "\n");
}
}
Upvotes: 0