在给定分隔符的情况下,C 中是否有任何预定义函数可以拆分字符串?假设我有一个字符串:
"Command:Context"
现在,我想将“Command”和“Context”存储到一个二维字符数组中
char ch[2][10];
或者两个不同的变量
char ch1[10], ch2[10];
我试过使用循环,效果很好。我只是好奇是否已经存在这样的功能,我不想重新发明轮子。请给出一个清晰的例子,非常感谢!
最佳答案
您可以使用 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;
}
输出:
Splitting string "Command:Context" into tokens:
Command
Context
关于C - 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884807/