Chirality
Chirality

Reputation: 745

Split string into array in C

Currently I'm trying to take a binary string, say 100101010, and split it into groups of three, so 100 101 010. Here's what I've written so far, for some reason it only prints the first group, 100 and then nothing after that.

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

int main(){

    int i;
    char *line = NULL;

    free(line);
    scanf("%ms", &line);

    printf("%d\n", strlen(line));

    for(i=0; i < strlen(line); ++i) {

        if ( i % 3 == 0 ){
            sprintf(line, "%c%c%c", line[i],line[i+1],line[i+2]);
            printf(line);
        }

    }

}

Upvotes: 0

Views: 120

Answers (2)

John3136
John3136

Reputation: 29266

sprintf(line, "%c%c%c", line[i],line[i+1],line[i+2]); writes your 3 characters into line, and so you overwrite your original string with your first group of 3. This means the next time through the loop i(4) is > strlen(line)(3) and so the loop stops.

Try:

/* Since 'line' and it's contents doesn't change in the loop we can
 * avoid the overhead of strlen() calls by doing it once and saving the
 * result.
 */
int len = strlen(line);

/* As mentioned in the comments, you could do
 * for(i = 0; i < len; i+=3) and then you don't need the
 * if (i%3) check inside the loop
 */
for(i=0; i < len; ++i) {
    if ( i % 3 == 0 ){
        /* This could be refactored to a loop
         * or scanf() to a different string but I say scanf is overkill
         * in this scenario...
         */
        char buffer[4];
        buffer[0] = line[i];
        buffer[1] = line[i+1];
        buffer[2] = line[i+2];
        buffer[3] = '\0';
        printf("%s\n", buffer);
        // Or just use puts() since we're not really doing 
        // any formatting.
    }
}

Upvotes: 2

cardiff space man
cardiff space man

Reputation: 1526

strlen(line) is reevaluated on each pass through the for loop, and you're changing the data that line points to inside the for loop by calling sprintf. Your sprintf makes line a 3-character string, hence you get only one trip through the loop in which i%3 is zero.

Upvotes: 0

Related Questions