如何使"strtok function"一次使用多个令牌字符串? 函数指针会解决这个问题吗?
How to make "strtok function" work with more than one Token String at a time? Would function pointers solve this?
strtok
函数使用一个静态变量将字符串解析为令牌。因此,当执行多个调用时,这会导致冲突。除了使用线程,我还能做以下事情吗:thx
-我可以使用函数指针在两个不同的位置分配函数吗?这会使"strtok"中的静态变量分配在两个不同的位置吗?
//breaking up first by Sentence and than by Word.
char phrase[] = "My dog has fleas.nAnd he gave them to me.";
char del1[] = "n";
char del2[] = " ";
char *token1;
char *token2;
token1 = strtok( phrase, del1);
while( token1 != NULL )
{
printf("Sentence: %s",token1);
token2 = strtok( token1, del2);
while( token2 != NULL ){
token2 = strtok( NULL, del2);
printf("WORD: %s",token2);
}
token1 = strtok( NULL, del1);
}
使用strtok_r()
(重入版本)。
也许可以使用strsep
而不是使用strtok
。请注意,我已经将嵌套循环提取为一个函数——嵌套循环太糟糕了!
已编辑:更改为直接使用strsep
/* print each word in a string*/
static void print_words(char *s)
{
while (s && *s) {
char *t = strsep(&s, " ");
printf("WORD: %sn", t);
}
}
void loop(void)
{
/* duplicate string in case it is read-only */
char *phrase = strdup("My dog has flees.nAnd he gave them to me.");
while (phrase) {
char *s = strsep(&phrase, "n");
printf("Sentence: %sn", s);
print_words(s);
}
}
使用strtok_r()。它还需要一个类似上下文的参数指针。
那是C还是C++?
如果是C++,则可以使用std::string
而不是char *
和std::string
方法来获得与使用strtok
相同的结果。
例如,您可以从find
和substr
方法中获得好处。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 使用用户定义函数的字符串反转
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 在c++构造函数中使用随机字符串生成器
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- C++:如何使函数只返回作为列表一部分的字符串
- 如何在C++中的同一函数中使用字符串和双精度
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 对函数 PlaySound 使用字符串变量
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 构造函数字符串参数未设置窗口标题
- C++默认构造函数:字符串参数与字符串参数()
- 使用函数C++字符串输入
- c++模板函数字符串类型不匹配