简体   繁体   English

如何从字符串中获取重复字符以及重复多少次

[英]how to get Repeated character from String and how many times it repeated

Hello I'm new in programming, and sorry for my English. 您好,我是编程新手,对不起我的英语。 So question is, for example: we have string "cabbaa" and I should get 1c1a2b2a 例如,问题是:我们有字符串“ cabbaa”,我应该得到1c1a2b2a

which means: 1 times'c', 1 times'a', 2 times'b', 2 times'a' 这意味着:1倍“ c”,1倍“ a”,2倍“ b”,2倍“ a”

I could write code which gets 1c3a2b : 我可以写得到1c3a2b代码:

public class test {

    static int i,j,k,c=0,w;
    static char m;  

    public static void main(String[] args) {
        frequencycount("cabbaa");
    }


    static void frequencycount(String s)

    {

        char[] z=new char[s.length()];
        for(w=0;w<s.length();w++)
        z[w]=s.charAt(w);
        for(i=0;i<w;i++)
        {
            char ch=z[i];
            for(j=i+1;j<w;j++)
            {
                if(z[j]==ch)
                {
                    for(k=j;k<(w-1);k++)
                    z[k]=z[k+1];
                    w--;
                    j=i;
                }
            }
        }

        int[] t=new int[w];
        for(i=0;i<w;i++)
        {
            for(j=0,c=0;j<s.length();j++)
            {
                if(z[i]==s.charAt(j))
                c++;
            }
            t[i]=c ;
            System.out.print(c+""+z[i]);
        }
    }

}

in this code I guess I compared all characters overall from string and got 1c3a2b , but I should get 1c1a2b2a . 在这段代码中,我想我比较了字符串中的所有字符,得到了1c3a2b ,但是我应该得到了1c1a2b2a

Any help appreciated. 任何帮助表示赞赏。

This should do the job: 这应该做的工作:

public class test {
    public static void main(String[] args) {
        frequencycount("cabbaa");
    }   

    static void frequencycount(String s) {
        StringBuilder output = new StringBuilder();
        Character previousCharacter = null;
        int counter = -1; 

        for (Character c : s.toCharArray()) {
            if (c.equals(previousCharacter)) {
                counter++;
            } else {
                if (previousCharacter != null) {
                    output.append(counter);
                    output.append(previousCharacter);
                }
                counter = 1;
                previousCharacter = c;
            }
        }

        if (previousCharacter != null) {
            output.append(counter);
            output.append(previousCharacter);
        }

        System.out.println("Res: " + output);
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM