问题描述
我试图来标记一个字符串,但我需要知道什么时候没有数据被两个标记之间看到。如标记化下面的字符串 A,B,C ,,, D,E
我需要了解两者之间的空槽 D时
和电子
'......对此我无法找出简单地使用的strtok()
。我尝试如下所示:
I am trying to tokenize a string but I need to know exactly when no data is seen between two tokens. e.g when tokenizing the following string "a,b,c,,,d,e
" I need to know about the two empty slots between 'd
' and 'e
'... which I am unable to find out simply using strtok()
. My attempt is shown below:
char arr_fields[num_of_fields];
char delim[]=",\n";
char *tok;
tok=strtok(line,delim);//line contains the data
for(i=0;i<num_of_fields;i++,tok=strtok(NULL,delim))
{
if(tok)
sprintf(arr_fields[i], "%s", tok);
else
sprintf(arr_fields[i], "%s", "-");
}
执行上面的code。与上述例子把字符,B,C,D,E为 arr_fields
第一五行这是不可取的。我需要每个字符的位置阵列的具体指标走:即如果有两个字符之间缺少一个角色,它应该被记录为是
Executing the above code with the aforementioned examples put characters a,b,c,d,e into first five elements of arr_fields
which is not desirable. I need the position of each character to go in specific indexes of array: i.e if there is a character missing between two characters, it should be recorded as is.
推荐答案
7.21.5.8 strtok函数在
标准说有关 strtok的
:
[#3]序列中的第一次调用搜索字符串
指向 S1
因为这是不是第一个字符
包含在当前分隔符字符串指向 S2
。
如果没有找到这样的字符,则有中没有标记
字符串指向 S1
和 strtok的
函数返回
空指针。如果找到这样的字符,这是
开始第一个令牌。
在上面的报价,我们可以读你不能使用 strtok的
作为解决您的具体问题,因为它会把在发现任何的顺序字符delims
为单标记。
In the above quote we can read you cannot use strtok
as a solution to your specific problem, since it will treat any sequential characters found in delims
as a single token.
您可以很容易地实现自己的版本 strtok的
,你想要做什么,看到的片段在这篇文章的末尾。
You can easily implement your own version of strtok
that does what you want, see the snippets at the end of this post.
strtok_single
利用了 strpbrk(字符常量* SRC,为const char * delims)
将返回一个指针任何字符中第一次出现的 delims 的是在空终止字符串中的的src 的
strtok_single
makes use of strpbrk (char const* src, const char* delims)
which will return a pointer to the first occurrence of any character in delims that is found in the null-terminated string src.
如果没有匹配的字符找到该函数将返回NULL。
If no matching character is found the function will return NULL.
strtok_single
char *
strtok_single (char * str, char const * delims)
{
static char * src = NULL;
char * p, * ret = 0;
if (str != NULL)
src = str;
if (src == NULL)
return NULL;
if ((p = strpbrk (src, delims)) != NULL) {
*p = 0;
ret = src;
src = ++p;
} else if (*src) {
ret = src;
src = NULL;
}
return ret;
}
样品使用
char delims[] = ",";
char data [] = "foo,bar,,baz,biz";
char * p = strtok_single (data, delims);
while (p) {
printf ("%s\n", *p ? p : "<empty>");
p = strtok_single (NULL, delims);
}
输出
foo
bar
<empty>
baz
biz
这篇关于需要在使用的strtok双令牌分离器之间似乎没有数据就知道()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!