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

在C语言中将字符串拆分为数组,c,arrays,string,C,Arrays,String,目前我正在尝试获取一个二进制字符串,比如100101010,并将其分成三组,即100101010。这是我到目前为止写的,出于某种原因,它只打印第一组,100,然后什么也不打印 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int i; char *line = NULL; free(line); scanf("%ms", &am

目前我正在尝试获取一个二进制字符串,比如100101010,并将其分成三组,即100101010。这是我到目前为止写的,出于某种原因,它只打印第一组,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);
        }

    }

}
#包括
#包括
#包括
int main(){
int i;
char*line=NULL;
自由线;
扫描频率(“%ms”和行);
printf(“%d\n”,strlen(行));
对于(i=0;i
strlen(line)在每次通过for循环时都会重新计算,您可以通过调用sprintf来更改该行指向for循环内部的数据。您的sprintf使行成为一个3个字符的字符串,因此您只能通过i%3为零的循环执行一次行程。

sprintf(行,“%c%c”、行[i]、行[i+1]、行[i+2])
将3个字符写入
,这样您就可以用第一组3个字符覆盖原始字符串。这意味着下一次通过循环
i
(4)是
>strlen(行)
(3),因此循环停止

尝试:

/*因为“行”及其内容在循环中不会改变,所以我们可以
*通过执行一次strlen()调用并保存
*结果。
*/
int len=strlen(直线);
/*如评论中所述,您可以这样做
*对于(i=0;i
为什么要释放空指针?这不是一件可怕的事情。如果释放空指针,实际上什么也不会发生。是的,我知道这是无害的,但是在释放指针之前的一行写着
line=null
,所以它是没有意义的。为什么要包含无意义的代码-这会使真正的问题更难发现。。。顺便说一句,你实际上并没有在结尾处腾出一条线,所以你有一条你不需要的线,而在你需要的地方却少了一条;-)非常好,谢谢!为了澄清,在循环中组合字符串使strlen每次都变小,这使得它只运行一次?是的
scanf(line…
更改了line的内容,因此strlen返回了一个不同的值。我将编辑上面的另一个注释。为什么不为(I=0;I?如果(I%3==0),则会删除
condition.@druciferre-+1从我这里得到。那更好。我的辩护是,我尽量让这样的东西接近OP的代码(即,不要一下子改变太多)@John3136:我可能建议对你正确而清晰的答案进行一个小的编辑:一般来说,printf不应该被赋予“不受控制的”其第一个参数的值。原因是printf()的实际实现可能会在尝试找出类似“%”的格式字符串时遇到困难,该字符串可能最终位于原始行中。只需替换FPUT(缓冲区、标准输出)你很好。根据我的经验,当格式字符串末尾有一个%后跟一个空格时,newlib的实现确实崩溃了。
/* 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.
    }
}