假设我输入了一个字符串:
INPUT:
My name is John
如何从包含所有单词的字符串中获取子字符串?
输出:
My
name
is
John
答案 0 :(得分:4)
使用strtok
int main ()
{
char str[] ="My name is John ";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ");
}
return 0;
}
答案 1 :(得分:1)
你可以使用strtok()
在那里你必须作为第一个参数给出字符串,并作为第二个参数给出令牌。
对于每个aditional调用,您必须将null设置为第一个参数,并将第一个出现的字符设置为要由\0
替换的字符串。
函数在子字符串上返回一个指针,因为\0
令牌正是你想要的。在你的情况下,你应该像这样使用它:
strtok (YourNonConstString, " ");
while (cp = strtok (NULL, " ") != NULL)
{
//Gotta do Here your stuff with cp as in each loop it contains the substring.
}