【问题标题】:Counting uppercase and lowercase characters of String and appending count to the character [duplicate]计算字符串的大写和小写字符并将计数附加到字符[重复]
【发布时间】:2016-03-14 11:35:59
【问题描述】:

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

例如如果字符串 = “AaaBBbCc”, 我需要输出为:“A1a2B2b1C1c1”。

I.E.大写“A”的计数,然后是小写“a”的计数,附加字符。

下面是代码 sn-p 直到我完成的地方。任何人都可以建议它是如何进行的。 我知道代码不符合标准:(

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

}

【问题讨论】:

标签: java run-length-encoding


【解决方案1】:

您在这里尝试完成的任务称为Run-length encoding。这有时被称为一种无损数据压缩形式,其中连续字符的长度附加到该字符的单个实例。这是来自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));
    }
}

【讨论】:

  • 如果输入字符串是“AaBBAAAaCac”会发生什么??我认为 ans 应该是 A4a3B2C1c1,不是吗?
  • @AtaurRahmanMunna 最初的问题似乎有点不清楚他们是否只想要所有大写和小写字母的计数(因为System.out.println("upper count is :"+upperCount+" &amp; lower count is: "+lowerCount);),就像运行长度编码一样(因为“例如。如果 string =“AaaBBbCc”,我需要输出为:“A1a2B2b1C1c1”。”),或者类似于您所说的输出按字母顺序排列的内容,每个字符数出现在字母之后(根据您所说)。
【解决方案2】:

你在正确的轨道上。如果您想计算出现的字母,不仅是大写还是小写,您可以创建 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]++; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 2014-10-03
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多