Search code examples
javastringintletters

java, how to find the amount of letter in a string without repeats


I'm trying to build a function, that gets a string of letters, and prints the amount of each letter in the string. for example: input: String = "aaabbaccxyxyx" output: 4a2b2c3x2y

This is what I've come up with:

public class Q1 {
    public static String numLetters(String s){
        String end = new String();
        int counter = 0;
        char c,d;
        for(int i=0; i<s.length();i++){
            c = s.charAt(i);
            for(int j=0; j<s.length();j++){
                d = s.charAt(j);
                if(c == d){
                    counter++;
                }
            }
            end = end + counter+c;
            counter = 0;
        }

        return end;
    }

but, this is the output: 4a4a4a2b2b4a2c2c3x2y3x2y3x A lot of repeats..

Any help how to make it right? Keep in mind, the function needs to return a string, not just prints it out. Thanks! =)


Solution

  • I would make an int array to keep the count of each letter in in the string. Because there are 26 letters, the length of the array should be 26:

    public static String numLetters(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            count[(int)(c - 'a')]++;
        }
        String ans = "";
        for (int i = 0; i < 26; i++) {
            if (count[i] != 0) {
                ans += String.valueOf(count[i]) + (char)(i + 'a');
            }
        }
        return ans;
    }