考虑以下具有两个不同字符串的场景:
Row1: MyID-MyName-MyAddress-MyNumber-MyNumber2-MyAlias
Row2: MyID-MyName-MyAddress-MyNumber--MyAlias
在第二个示例中,MyNumber2
的值丢失了。我需要使用 strtok()
提取每个属性。到目前为止,这是我的代码:
MyID = strtok (str, "-"); //where 'str' is the full string
MyName = strtok (NULL, "-");
MyAddress = strtok (NULL, "-");
MyNumber = strtok (NULL, "-");
MyNumber2 = strtok (NULL, "-");
MyAlias = strtok (NULL, "-");
第一个示例运行良好,我能够将每个属性 存储在变量中。但是,在第二个示例中,我遇到了麻烦:
当进入变量 MyNumber2
时,strtok()
不会返回空字符串(正如我所希望的那样)。相反,它会通读字符串,直到第一个字符与分隔符 "-"
不匹配,从而忽略字符串中存在的 empty 值。
有没有可能每个分隔符只分割一次字符串?
最佳答案
我认为您应该改用标准函数 strchr
。例如
#include <stdio.h>
#include <string.h>
int main( void )
{
char s[] = "MyID-MyName-MyAddress-MyNumber--MyAlias";
for ( char *p = s, *q = s; p != NULL; p = q )
{
q = strchr( p, '-' );
if ( q )
{
printf( "\"%*.*s\"\n", ( int )(q - p ), ( int )( q - p ), p );
++q;
}
else
{
printf( "\"%s\"\n", p );
}
}
}
程序输出为
"MyID"
"MyName"
"MyAddress"
"MyNumber"
""
"MyAlias"
关于c - 一次只从 strtok 获取一个 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471849/