C - 拆分字符串

dpp*_*dpp 1 c string split

在C中是否有任何预定义函数可以在给定分隔符的情况下拆分字符串?说我有一个字符串:

"Command:Context"
Run Code Online (Sandbox Code Playgroud)

现在,我想将"Command"和"Context"存储到二维字符数组中

char ch[2][10]; 
Run Code Online (Sandbox Code Playgroud)

或两个不同的变量

char ch1[10], ch2[10];
Run Code Online (Sandbox Code Playgroud)

我尝试使用循环,它工作正常.我只是好奇是否有这样的功能已经存在,我不想重新发明轮子.请提供一个明确的例子,非常感谢!

Alo*_*ave 6

你可以使用strtok

在线演示:

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="Command:Context";
    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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Splitting string "Command:Context" into tokens:
Command
Context
Run Code Online (Sandbox Code Playgroud)