如何将字符串拆分为一个标记,然后将它们保存在一个数组中?
具体来说,我有一个字符串"abc/qwe/jkh".我想分开"/",然后将令牌保存到数组中.
输出将是这样的
array[0] = "abc"
array[1] = "qwe"
array[2] = "jkh"
Run Code Online (Sandbox Code Playgroud)
请帮我
rli*_*lib 30
#include <stdio.h>
#include <string.h>
int main ()
{
char buf[] ="abc/qwe/ccd";
int i = 0;
char *p = strtok (buf, "/");
char *array[3];
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, "/");
}
for (i = 0; i < 3; ++i)
printf("%s\n", array[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 strtok()
char string[]= "abc/qwe/jkh";
char *array[10];
int i=0;
array[i] = strtok(string,"/");
while(array[i]!=NULL)
{
array[++i] = strtok(NULL,"/");
}
Run Code Online (Sandbox Code Playgroud)
strtok()是个坏主意不要strtok()在正常代码中使用,strtok()使用static有一些问题的变量。嵌入式微控制器上有一些用例,其中static变量是有意义的,但在大多数其他情况下避免使用它们。strtok()当超过 1 个线程使用它、在中断中使用它或在其他一些情况下在连续调用 之间处理多个输入时,会出现意外行为strtok()。考虑这个例子:
#include <stdio.h>
#include <string.h>
//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
char *p = strtok(input, "/");
while(p)
{
printf("%s, ",p);
p = strtok(NULL, "/");
}
}
int main(void)
{
char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
char *p = strtok(buffer, ":");
while(p)
{
printContent(p);
puts(""); //print newline
p = strtok(NULL, ":");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可能期望输出:
abc, def, ghi,
ABC, DEF, GHI,
Run Code Online (Sandbox Code Playgroud)
但你会得到
abc, def, ghi,
Run Code Online (Sandbox Code Playgroud)
这是因为您调用strtok()了重置中生成的printContent()内部状态。返回后, 的内容为空,下次调用返回。strtok()main()strtok()strtok()NULL
当你使用POSIX系统时就可以使用strtok_r(),这个版本不需要static变量。如果您的库没有提供,strtok_r()您可以编写自己的版本。这应该不难,而且 Stackoverflow 不是编码服务,您可以自己编写。