我正在解析3个并行的值,这些值用特定的分隔符分隔.
token1 = strtok_s(str1, separator, &nextToken1);
token2 = strtok_s(str2, separator, &nextToken2);
token3 = strtok_s(str3, separator, &nextToken3);
while ((token1 != NULL) && (token2 != NULL) && (token3 != NULL))
{
//...
token1 = strtok_s(NULL, separator, &nextToken1);
token2 = strtok_s(NULL, separator, &nextToken2);
token3 = strtok_s(NULL, separator, &nextToken3);
}
Run Code Online (Sandbox Code Playgroud)
假设' - '是我的分隔符.行为是没有连续分隔符的字符串:
1-2-3-45
Run Code Online (Sandbox Code Playgroud)
将有效地导致这些部分中的每一个:
1
2
3
45
Run Code Online (Sandbox Code Playgroud)
但是,带有两个连续分隔符的字符串:
1-2--3-45
Run Code Online (Sandbox Code Playgroud)
不会产生0长度的字符串,跳过一个字符串,结果是:
1
2
3
45
Run Code Online (Sandbox Code Playgroud)
并不是
1
2
3
45
Run Code Online (Sandbox Code Playgroud)
哪种解决方法或策略更适合获取所有实际部件,包括0长度部件?如果可能的话,我想避免重新实现strtok_s.
我正在尝试使用strtok().以下是我写的一段代码.它不起作用,但", '"无限打印.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[]="this, by the way, is a 'sample'";
char *tokens;
tokens = strtok(str, ", '");
//printf("%s\n",tokens);
//printf("%s\n", str);
while(tokens!=NULL)
{
printf("%s\n", tokens);
tokens = (NULL, ", '");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是strtok()手册页中的代码,完全正常.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf …Run Code Online (Sandbox Code Playgroud)