2015-10-27 319 views
0

當前我正在嘗試取一個二進制字符串,比如說100101010,並將其拆分爲三個組,因此10010110。以下是我迄今爲止所寫的內容,由於某些原因,它僅適用於打印第一個組,然後在此之後沒有任何內容。將字符串拆分爲數組C

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

    } 

} 
+0

你爲什麼要釋放一個NULL指針? – John3136

+0

這並不是一件可怕的事情。如果您釋放空指針,則實際上不會發生任何事 – Chirality

+1

的確,我知道它是無害的,但是在免費說'line = NULL'之前的那一行,所以它沒有意義。爲什麼包括無意義的代碼 - 它使真正的問題難以發現......順便說一句 - 你實際上並沒有在最終釋放線路,所以你有一個空閒的地方你不需要它,並且在你做的地方缺少一個; - ) – John3136

回答

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. 
    } 
} 
+0

這很好,謝謝!爲了澄清,將循環內的字符串組合使得strlen每次更小,這使得它只能運行一次? – Chirality

+0

是的。 'scanf(line ...'改變了行的內容,所以strlen返回了一個不同的值,我將編輯上面的另一個註釋 – John3136

+1

爲什麼不行'for(i = 0; i

0

的strlen(線)重新評估每個經過的循環,你改變了數據線點裏面的for循環調用sprintf的。你的sprintf使行成爲3個字符的字符串,因此你只能通過i%3爲零的循環的一次行程。