2014-01-13 106 views
0

一定規模的字符串比方說,我有一個字符串「abcd1234efgh」。我想分裂成長度爲4的子字符串,如: abcd efgh分割字符串轉換成用C

我的C是生鏽的。這是我寫的:

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

int main(void){ 

int i,j; 
char values[32]="abcd1234efgh"; 
char temp[10]; 

for(i=0;values[i]!='\0';){ 
    for (j=0;j<4;j++,i++){ 
     temp[i]=values[j]; 
     printf("%c\n",values[j]); 
    } 
printf("string temp:%s\n",temp); 
} 

return 0; 
} 

輸出顯然是錯誤的,因爲我沒有保存原始字符串的索引。有關如何解決此問題的任何提示?對於長度不是4的倍數的字符串,我想用空格填充短的子字符串。

+0

溫度只需要持有4個字符。因爲現在我每次迭代都會得到前4個字符。換句話說,它重複並重復同樣的第一個4。我想要的是獲得前四個,然後是後四個等,以便我可以將它們饋送到另一個緩衝區。 – SamSong

回答

3

這應該做的伎倆,如果你正在尋找只打印:如果你想要做

int len = strlen(values); 
for (int off = 0; off < len; off += 4) 
    printf("%.4s\n", values+off); 

別的東西(以及)與4組,那麼我會考慮:

int len = strlen(values); 
for (int off = 0; off < len; off += 4) 
{ 
    strncpy(temp, values+off, 4); 
    temp[4] = '\0'; 
    …do as you will with temp… 
} 
+0

很好的答案,謝謝。 – SamSong

0

注意:代碼爲4組打印,而不是打破並存儲字符串,如果大小4

,如果這是你問什麼

#include<stdio.h> 
#include<string.h> 
int main(void) 
{ 
int i; 
char values[32]="abcd1234efgh"; 
for(i=0;values[i]!='\0';) 
{ 
    if(i % 4 == 0) printf("\n"); 
    printf("%c",values[i]); 
} 
return 0; 
} 

這應該做的伎倆

+0

一個小問題是,如果字符的'values'數量不是4的倍數,你的輸出不會以新行結束。 –

+0

不應該有循環結束後,螞蟻的問題只是增加一個換行符 你從來沒有水晶的問題 – dips

+0

同樣的錯誤與您的解決方案 – dips

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

int main(void){ 

int i,j; 
char values[32]="abcd1234efgh12"; 
char temp[10]; 

for(i=0;values[i]!='\0';){ 
    for (j=0;j<4;j++,i++){ 
     temp[j]=values[i]; 
    } 
    while(j<4) 
    { 
     temp[j]=' '; 
    } 
    temp[j]='\0'; 
printf("string temp:%s\n",temp); 
} 

return 0; 
} 
+0

任何人都可以發表評論解釋了爲什麼否決這個答案 – michaeltang

+0

也許,有一個在這個程序中潛在的錯誤。我注意到下面。 (1)'while(j <4)'這是行不通的。 (2)values [i]!='\ 0'被複制到這個地方之外。 – BLUEPIXY

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

int main() { 
    char *str = "abcd1234efgh"; 
    size_t sub_len = 4; 
    size_t len = strlen(str); 
    size_t n = len/sub_len; 
    if(n * sub_len < len) 
     n += 1; 

    char temp[n][sub_len+1]; 
    int i; 
    for (i = 0; i < n; ++i){ 
     strncpy(temp[i], str + i*sub_len, sub_len); 
     temp[i][sub_len]='\0'; 
     printf("string temp:%s\n", temp[i]); 
    } 
    return 0; 
}