计算字符串的大写和小写字符并将计数附加到字符

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

我正在尝试打印字符串的输出以查找其中大写和小写的计数。

例如如果字符串 = "AaaBBbCc", 我需要输出为:"A1a2B2b1C1c1".

即大写字母计数 'A' 然后小写字母计数 'a',附加字符。

下面是我完成的代码片段。任何人都可以建议如何进行。 我知道代码不符合标准:(

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);     

}

你走在正确的轨道上。如果你想计算出现的字母,不仅是大写还是小写,你可以创建 2 int[] 数组 upperCaseCountlowerCaseCount = new int[26]。您可以使用这些数组来计算出现的字母。

提示 你可以利用 char 可以用作 int 的事实来确定你应该增加哪个索引:

int index = ? //'a' should be 0 for lower, and 'A' should be 0 for upper
lowerCaseCount[index]++ or upperCaseCount[index]++; 

您在此处尝试完成的称为 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,应该可以解决您的问题:

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));
    }
}