cstringrun-length-encoding

Repeated characters in a string, C program


I have a trouble with my C-code. My input is a string. The calculator has to count how many times the first character in the string repeats until it finds another different character and write down the number of times it appears and the character it considers. Then it starts again considering the next character. The following example might clear you:

  1. If the input is RRDDuuuRRRuuu, the output must be 2R 2D 3u 3R 3u.

I cannot (and I do not want to) use too many indices, but I do not manage to find a solution using few indices.

#include <stdio.h>
#include <string.h>

int main()
{
    char str1[3000]; // Declaring string arrays
    int i, j; // Declaring variables for length, iteration, counts
    long unsigned int n;
    
    printf("Enter a string: ");
    
    scanf("%s", str1); // Inputting a string from the user
    
    printf("Its first character is %c\n", str1[0]);
    
    n = strlen(str1);
    
    printf("String length is %lu\n", n);
    
    i = 0;
    do { i++; } while (str1[i] == str1[0]);
    printf("%d%c ", i, str1[0]);
    j = i - 1;
    do { j++; } while (str1[j] == str1[i]);
    printf("%d%c ", j - i, str1[i]);
    
    return 0;
}

Solution

  • This will only be able to count the first two characters:

    i=0;
    do {i++;} while (str1[i]==str1[0]);
    printf("%d%c ",i,str1[0]);           // first
    j=i-1;
    do {j++;} while (str1[j]==str1[i]);
    printf("%d%c ",j-i,str1[i]);         // second
    

    You need to keep going until the end of the string. You however don't need a separate index for each character. Just loop around each character counting.

    Example:

    void print_rep(const char *str) {
        while (*str) {                   // while not at the null terminator
            unsigned count = 0;          // init count
            const char ch = *str;        // save the character
            do {
                ++count;                 // increase the count
                ++str;                   // step pointer to the next character
            } while(*str == ch);         // loop until a new character is found
            printf("%u%c ", count, ch);  // print result
        }                                // go back to count the next character
        putchar('\n');
    }
    

    Demo