在C中将字符串拆分为数组

时间:2015-10-27 23:57:37

标签: c arrays string

目前我正在尝试使用二进制字符串,例如100101010,并将其拆分为三个一组,所以100 101 010.这是我到目前为止所写的内容,由于某种原因它只打印第一组,然后是100,然后没有打印。

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

    }

}

2 个答案:

答案 0 :(得分:2)

sprintf(line, "%c%c%c", line[i],line[i+1],line[i+2]);将您的3个字符写入line,因此您使用第一组3覆盖原始字符串。这意味着下一次循环i(4)是> strlen(line)(3)因此循环停止。

尝试:

/* 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.
    }
}

答案 1 :(得分:0)

strlen(line)在每次通过for循环时被重新评估,并且您通过调用sprintf来更改行指向for循环内部的数据。你的sprintf使一行成为一个3个字符的字符串,因此你只能在i%3为零的循环中获得一次。