Search code examples
javarun-length-encoding

Counting uppercase and lowercase characters of String and appending count to the character


I am trying to print the output of a String to find the count of uppercase and lowercase in it.

E.g. if string = "AaaBBbCc", I need the output as : "A1a2B2b1C1c1".

I.E. count of uppercase 'A' then count of lowercase 'a', appending with the characters.

Below is the code snippet till where I have done. Can any one suggest how it goes. I know code is not up-to the mark :(

public static void main(String[] args) {
    String str = "AaaBBbCc";
    int upperCount=0;
    int lowerCount=0;

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if(ch>='A' && ch<='Z'){
             upperCount++;
             System.out.println("Uppercase letter is : "+ch+upperCount);

    }
     if(ch>='a' && ch<='z'){
        lowerCount++;
        System.out.println("Lower case letter is : "+ch+lowerCount);
    }
}
    System.out.println("upper count is :"+upperCount+" & lower count is: "+lowerCount);     

}


Solution

  • What you are trying to accomplish here is called Run-length encoding. This is sometimes referred to as a form of lossless data compression in which the length of a continuous character is appended to a single instance of that character. Here is a modified version from RosettaCode that should do the trick for you:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class RunLengthEncoding {
    
        public static String encode(String source) {
            StringBuffer dest = new StringBuffer();
            for (int i = 0; i < source.length(); i++) {
                int runLength = 1;
                while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
                    runLength++;
                    i++;
                }
                /* We will swap these so they fit your format of [Letter][Count]
                dest.append(runLength);
                dest.append(source.charAt(i));
                */
                dest.append(source.charAt(i));
                dest.append(runLength);
            }
            return dest.toString();
        }
    
        public static void main(String[] args) {
            String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
            System.out.println(encode(example));
        }
    }