2012-09-06 44 views
3

我有一個格式爲<item1>:<item2>:<item3>的字符串中的字符數組是什麼是最好的分解方式,以便我可以分別打印不同的項目?我應該循環訪問數組,還是有一些可以幫助的字符串函數?替換字符串中的字符C

+2

您將受益於閱讀任何初學者ç書,甚至K&R –

+0

退房'的sscanf()'或'的strtok()'或做你的實現並不難.. – Jack

回答

1

我會用sscanf功能

char * str = "i1:i2:i3"; 
char a[10]; 
char b[10]; 
char c[10]; 
sscanf(str, "%s:%s:%s", a, b, c); 

這是不安全的,因爲它很容易受到緩衝區溢出。在Windows中,有sscanf_s作爲安全破解。

1

您可以嘗試strtok: 這裏是一些示例代碼,以獲取被分隔的子字符串, - 或|

#include <stdio.h> 
#include <string.h> 
int main(int argc,char **argv) 
{ 
char buf1[64]={'a', 'a', 'a', ',' , ',', 'b', 'b', 'b', '-', 'c','e', '|', 'a','b', }; 
/* Establish string and get the first token: */ 
char* token = strtok(buf1, ",-|"); 
while(token != NULL) 
    { 
/* While there are tokens in "string" */ 
     printf("%s ", token); 
/* Get next token: */ 
     token = strtok(NULL, ",-|"); 
    } 
return 0; 
} 
+0

-1,這是一個對從字符串文字初始化的字符指針運行'strtok()'真的是個壞主意。文字是隻讀的,但'strtok()'修改它。這很容易崩潰。 – unwind

+0

感謝您的建議。我只是很快寫了樣本,但沒有考慮到這個問題。謝謝。 – wbao

0

strtok是最好的選擇,在這裏想補充兩兩件事:

1)strtok修改/操縱原始的字符串,並剝離出來的分隔符,並

2)如果你有一個多線程程序,你可以使用strtok_r這是線程安全/可重入版本。

0

只需遍歷字符串,每次點擊':'時,打印自上次出現':'以來已經讀取的任何內容。

#define DELIM ':' 


char *start, *end; 

start = end = buf1; 

while (*end) { 
    switch (*end) { 
     case DELIM: 
      *end = '\0'; 
      puts(start); 
      start = end+1; 
      *end = DELIM; 
      break; 
     case '\0': 
      puts(start); 
      goto cleanup; 
      break; 
    } 
    end++; 
} 

cleanup: 
// ...and get rid of gotos ;)