如何计算字符串中特定字符的数量?

时间:2011-10-23 04:42:20

标签: java string

给定一个字符串,我怎样才能算出字符串中每个字符重复的次数 例如:aaaabbaaDD 输出:4a2b2a2D

public static void Calc() {

        Input();

        int count = 1;

        String compressed = "";

        for (int i = 0; i < input.length(); i++) {

            if (lastChar == input.charAt(i)) {

                count++;

                compressed += Integer.toString(count) + input.charAt(i);
            }

            else {

                lastChar = input.charAt(i);
                count = 1;
            }

        }

        System.out.println(compressed);

    }

4 个答案:

答案 0 :(得分:1)

你要找的是“游程编码”。这是执行此操作的工作代码;

 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 public class RunLengthEncoding {

public static String encode(String source) {
    StringBuffer dest = new StringBuffer();
   //  iterate through input string 
   // Iterate the string N no.of.times where N is size of the string to find run length for each character
    for (int i = 0; i < source.length(); i++) {
        // By default run Length for all character is one
        int runLength = 1;

        // Loop condition will break when it finds next character is different from previous character. 
        while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
            runLength++;
            i++;
        }
        dest.append(runLength);
        dest.append(source.charAt(i));
    }
    return dest.toString();
}

public static String decode(String source) {
    StringBuffer dest = new StringBuffer();
    Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
    Matcher matcher = pattern.matcher(source);
    while (matcher.find()) {
        int number = Integer.parseInt(matcher.group());
        matcher.find();
        while (number-- != 0) {
            dest.append(matcher.group());
        }
    }
    return dest.toString();
}

public static void main(String[] args) {
    String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
    System.out.println(encode(example));
    System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
 }

答案 1 :(得分:1)

该程序首先在字符串中查找唯一的字符或数字。然后它将检查发生的频率。 该程序将大写和小写视为不同的字符。如果需要,可以使用ignorecase方法修改它。


import java.io.*;
public class RunLength {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws IOException {
        System.out.println("Please enter the string");
        String str = br.readLine();//the input string is in str
        calculateFrequency(str);
    }
    private static void calculateFrequency(String str) {
        int length = str.length();
        String characters[] = new String[length];//to store all unique characters in string
        int frequency[] = new int[length];//to store the frequency of the characters
        for (int i = 0; i < length; i++) {
            characters[i] = null;
            frequency[i] = 0;
        }

//To get unique characters char temp; String temporary; int uniqueCount = 0; for (int i = 0; i < length; i++) { int flag = 0; temp = str.charAt(i); temporary = "" + temp; for (int j = 0; j < length; j++) { if (characters[j] != null && characters[j].equals(temporary)) { flag = 1; break; } } if (flag == 0) { characters[uniqueCount] = temporary; uniqueCount++; } } // To get the frequency of the characters for(int i=0;i<length;i++){ temp=str.charAt(i); temporary = ""+temp; for(int j=0;i<characters.length;j++){ if(characters[j].equals(temporary)){ frequency[j]++; break; } } } // To display the output for (int i = 0; i < length; i++) { if (characters[i] != null) { System.out.println(characters[i]+" "+frequency[i]); } } }}

答案 2 :(得分:0)

一些提示:在代码示例中,您还需要在运行结束时(更新count时)将lastChar重置为0。并且您需要输出最终运行(循环完成后)。在这两种情况之间你需要某种elsecontinue

答案 3 :(得分:0)

@Balarmurugan k的解决方案更好 - 但只是通过改进你的代码我想出了这个 -

    String input = "aaaabbaaDD";
    int count = 0;
    char lastChar = 0;
    int inputSize = input.length();
    String output = "";
    for (int i = 0; i < inputSize; i++) {
        if (i == 0) {
            lastChar = input.charAt(i);
            count++;
        } else {
            if (lastChar == input.charAt(i)) {
                count++;
            } else {
                output = output + count + "" + lastChar;
                count = 1;
                lastChar = input.charAt(i);
            }
        }
    }
    output = output + count + "" + lastChar;
    System.out.println(output);