2016-06-25 219 views
0

所以我需要幫助將一個字符串分隔成多個單獨的字符串。 例如,假設我有類似:分隔字符串C

char sentence[]= "This is a sentence."; 

,我想將它拆分到:

char A[]="This"; 
char B[]="is"; 
char C[]="a"; 
char D[]="sentence."; 
+1

直視'的strtok()' – Haris

+1

您可能需要的strdup太使用。 (你不能創建一個常量) – enhzflep

+2

'句子'不是一個常量 - 它只是初始化的。 –

回答

0

如上所述,您可以使用strtok()做這個工作。用法是不是很直觀:

char sentence[]= "This is a sentence."; // sentence is changed during tokenization. If you want to keep the original data, copy it. 

char *word = strtok(sentence, " ."); // Only space + full stop for having a multi delimiter example 
while (word!=NULL) 
{ 
    // word points to the first part. The end of the word is marked with \0 in the original string 
    // Do something with it, process it, store it 
    … 
word = strtok(NULL, " ."); // To get the next word out of sentence, pass NULL 
}