文字が文字列内の連続的に出現する回数を数えます

ミスル:

私は、Javaに新たなんです。私は彼らの数と一緒に文字列に存在する文字を印刷しようとしています。同じ文字がその隣に存在する場合、カウントは増加します。

例:

I / O:Sssgs

A / 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]);
        }
    }

入力が> HelloWorldのです

期待される出力が> H1 E1 L2 O1 W1 O1 R1、L1、D1であるべきです

ラファウSokalski:

私はちょうどあなたのコードで、それはそれがどのように見えるかです下にいくつかの修正をしました。

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

私はちょうど出現の文字とそれ数を読んで、その後の反復でその数をジャンプしたときにほとんど変化はプリントDistinctsにありました。それは私が異なっている次の文字の上に停止します

「Sssgs」の出力は、「S1s2g1s1」であり、「HelloWorldの」ため「H1e1l2o1W1o1r1l1d1」であります

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=180968&siteId=1
おすすめ