Count the number of times a character appears in a contiguous manner in a string

Misr :

I'm new to Java. I'm trying to print the characters present in the string along with their count. The count only increments when the same character is present next to it.

Ex:

I/O : Sssgs

O/P : S1s2g1s1

Counting the occurence of each character gives the count of the full count regardless of the characters not being present next to each other. Tampering with the i & j loops gives an OutOfBounds error.

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

The Input is > HelloWorld

The expected output should be > H1 e1 l2 o1 W1 o1 r1 l1 d1

Rafał Sokalski :

I just made some corrections in your code and below it is how it looks like:

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

Most changes was in Prints Distincts when I just read character and it number of occurence and then jump that number in iteration. It lets me stops on the next character which is different

The output for "Sssgs" is "S1s2g1s1" and for "HelloWorld" is "H1e1l2o1W1o1r1l1d1"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=69948&siteId=1