如何从C中的字符串中获取包含单词的子字符串?

时间:2014-09-19 06:05:59

标签: c string substring

假设我输入了一个字符串:

INPUT:

My name is John 

如何从包含所有单词的字符串中获取子字符串?

输出:

My
name
is
John

2 个答案:

答案 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() 在那里你必须作为第一个参数给出字符串,并作为第二个参数给出令牌。 对于每个ad​​itional调用,您必须将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.
}