如何在第一个空格处拆分字符串并将字符串交给不同的变量?

时间:2017-03-05 06:37:42

标签: c string spaces

我需要找到一种方法在中间的空格处分割两个单词的字符串。

然后我需要将两个新字符串分配给两个变量(x和y)。

我希望第二个字符串从空格后面的下一个字母的位置开始。

我对此很新,所以欢迎任何简单的建议。

2 个答案:

答案 0 :(得分:2)

您可以使用strchr函数查找字符串中第一次出现的' '。然后你可以这样做:

char* wholeSentence = "hello world";
char* startOfSecond = strchr(wholeSentence, ' '); // " world";
size_t lengthOfFirst = startOfSecond - wholeSentence;
char* first = (char*)malloc((lengthOfFirst + 1) * sizeof(char));
strncpy(first, wholeSentence, lengthOfFirst)); // "hello"

你可以用同样的方式找到第二个。

答案 1 :(得分:0)

使用 strtok
示例:

 char x[80] = "This is";
 const char s[] = " ";
 char *y;
 strtok(x, s); // first string
 y = strtok(NULL, s); // second string