计算字符在字符串中以连续方式出现的次数

Mis*_*isr 5 java arrays frequency

我是Java新手。我正在尝试打印字符串中存在的字符及其计数。仅当旁边有相同字符时,计数才会增加。

例如:

I / O:Sssgs

O / P:S1s2g1s1

对每个字符的出现进行计数将得出全部计数的计数,而与相邻的字符不存在无关。篡改i和j循环会出现OutOfBounds错误。

      //ch[] is the String converted to a character array.
     //count[] is an array to store count of the characters      

    //Checks if present char and next char are same and increments count
    for(int i=0;i<ch.length;i++)    
    {
        count[i]=0;
        for(int j=0;j<ch.length;j++)
        {
            if(ch[i]==ch[j])
            {
                count[i]++;
            }
        }
    }

    //Prints Distinct char
    for(int i=0;i<ch.length;i++)
    {
        int j;
        for(j=0;j<i;j++)
        {
            if(ch[i]==ch[j])
            {
                break;
            }
        }

        if(i==j)
        {
            System.out.print(ch[i]+" "+count[i]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

输入> HelloWorld

预期输出应> H1 e1 l2 o1 W1 o1 r1 l1 d1