如何安全解析制表符分隔符字符串?例如: 测试\tbla-bla-bla\t2332 ?
最佳答案
strtok()
是一个标准函数,用于解析带有任意定界符的字符串。但是,它不是线程安全的。您选择的 C 库可能有一个线程安全的变体。
另一种符合标准的方式(刚刚写的,未测试):
#include <string.h>
#include <stdio.h>
int main()
{
char string[] = "foo\tbar\tbaz";
char * start = string;
char * end;
while ( ( end = strchr( start, '\t' ) ) != NULL )
{
// %s prints a number of characters, * takes number from stack
// (your token is not zero-terminated!)
printf( "%.*s\n", end - start, start );
start = end + 1;
}
// start points to last token, zero-terminated
printf( "%s", start );
return 0;
}
关于c - 如何安全解析制表符分隔的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839664/