从strtok的获取零长度字符串() [英] Obtaining zero-length string from strtok()
问题描述
我有一个包含数据的CSV文件,如
I have a CSV file containing data such as
value;name;test;etc
而我试图用 strtok的分裂(字符串,)
。但是,此文件可以包含零长度的数据,如:
which I'm trying to split by using strtok(string, ";")
. However, this file can contain zero-length data, like this:
value;;test;etc
这的strtok()
跳过。有没有一种方法可以让我避免 strtok的
从跳过像这样零长度的数据?
which strtok()
skips. Is there a way I can avoid strtok
from skipping zero-length data like this?
推荐答案
一个可能的选择是使用BSD函数 strsep()
而不是的strtok()
,如果有的话。
从手册页:
A possible alternative is to use the BSD function strsep()
instead of strtok()
, if available.
From the man page:
的 strsep()
功能旨在为一个更换的strtok()
功能。而的strtok()
函数应该是preferred
便携性的原因(它符合ISO / IEC 9899:1990(ISO C90))
它无法处理空字段,即通过检测分隔的字段
两个相邻的分隔符,或者也可以用于除一个更
同时单个字符串。在 strsep()
功能最早出现在
4.4BSD。
The
strsep()
function is intended as a replacement for thestrtok()
function. While thestrtok()
function should be preferred for portability reasons (it conforms to ISO/IEC 9899:1990 ("ISO C90")) it is unable to handle empty fields, i.e., detect fields delimited by two adjacent delimiter characters, or to be used for more than a single string at a time. Thestrsep()
function first appeared in 4.4BSD.
一个简单的例子(也是从那个男人页面复制):
A simple example (also copied from that man page):
char *token, *string, *tofree;
tofree = string = strdup("value;;test;etc");
while ((token = strsep(&string, ";")) != NULL)
printf("token=%s\n", token);
free(tofree);
输出:
token=value
token=
token=test
token=etc
这样的空字段正确处理。
so empty fields are handled correctly.
当然,正如其他人已经说过,没有这些简单的分词功能手柄
引号内的分隔符正确的痕迹,因此,如果这是一个问题,你应该使用
一个的正确的CSV解析库。
Of course, as others already said, none of these simple tokenizer functions handles delimiter inside quotation marks correctly, so if that is an issue, you should use a proper CSV parsing library.
这篇关于从strtok的获取零长度字符串()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!