在C中分隔一个字符串

时间:2016-06-25 18:58:01

标签: c arrays string char

所以我需要帮助将一个字符串分成多个单独的字符串。 例如,假设我有类似的东西:

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

我希望将其拆分为:

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

2 个答案:

答案 0 :(得分:1)

同样的问题,不同的分割要求:

  

Split string with delimiters in C

答案 1 :(得分: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
}