首页 > 解决方案 > 计算一个字符在字符串中以连续方式出现的次数

问题描述

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

前任:

输入/输出:Sssgs

输出/输出: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]);
        }
    }

输入是 > HelloWorld

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

标签: javaarraysfrequency

解决方案


我刚刚对您的代码进行了一些更正,下面是它的样子:

public static void main(String[] args) {
    String s = "Sssgs";
    char[] ch = s.toCharArray();
    int[] count = new int[20];

       for(int i=0;i<ch.length;i++)    
        {
            count[i]=0;
            for(int j=i;j<ch.length;j++)
            {
                if(ch[i]==ch[j])
                {
                    count[i]++;
                } else {
                    break;
                }
            }
        }

        //Prints Distinct char
        for(int i=0;i<ch.length;i += count[i])
        {
            System.out.print(ch[i] + "" +count[i]);
        }
}

当我刚刚读取字符及其出现次数然后在迭代中跳跃该数字时,大多数变化都发生在 Prints Distincts 中。它让我停在下一个不同的角色上

“Sssgs”的输出是“S1s2g1s1”,“HelloWorld”的输出是“H1e1l2o1W1o1r1l1d1”


推荐阅读