当第一个标记为空时需要 strtok 函数的帮助 [英] Need help in strtok function when the first token is null

查看:31
本文介绍了当第一个标记为空时需要 strtok 函数的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要 strtok 函数的帮助

Need help in strtok function

#include<stdio.h>
#include<string.h>

int main()
{
    char string[100], *ptr = NULL;

    memset(string, 0, 100);
    strcpy(string, "abc#efg#xyz");

    ptr = strtok(string, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);

    ptr = strtok(NULL, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);

    ptr = strtok(NULL, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);
    return 0;
}

输出是

ptr = [abc]
ptr = [efg]
ptr = [xyz]

这很好,但是如果第一个标记为空,则对 strtok 的第一次调用将返回第二个标记.我的理解是它会在第一次调用时返回一个空值,因为令牌不存在.

This is fine, but when if the first token is null then the first call to strtok returns the second token. My understanding is that it will return a null in the first call as the token is not present.

#include<stdio.h>
#include<string.h>

int main()
{
    char string[100], *ptr = NULL;

    memset(string, 0, 100);
    strcpy(string, "#efg#xyz");

    ptr = strtok(string, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);

    ptr = strtok(NULL, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);

    ptr = strtok(NULL, "#");
    fprintf(stderr, "ptr = [%s]\n", ptr);
    return 0;
}***

输出是

ptr = [efg]
ptr = [xyz]
ptr = [(null)]

推荐答案

来自 http://www.cplusplus.com/reference/cstring/strtok/

要判断一个token的开头和结尾,函数先从起始位置扫描 未包含的第一个字符在分隔符中

To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters

所以我认为这是您所看到的正确行为.strtok() 从您的第一个字符开始,将其视为分隔符,忽略它,并向前寻找第一个非分隔符字符.

So I think that this is the correct behavior you are seeing. strtok() starts from your first character, see's it as a delimeter, ignores it, and seeks forward for the first non-delimiter character.

我想解决这个问题的方法是自己检查第一个字符是否不是分隔符.

I guess the way around it is to check that the first character is not a delimiter yourself.

也检查了 C 标准 (ISO/IEC 9899:1999(E)) 并且定义相同:

Checked C standard (ISO/IEC 9899:1999(E)) too and the definition is the same:

序列中的第一个调用搜索s1指向的字符串对于当前分隔符中不包含的第一个字符s2

The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2

事实上,标准在 7.21.5.8 中给出了一个例子,第 8 点:

In fact, the standard gives an example in 7.21.5.8, bullet point 8:

#include <string.h>
static char str[] = "?a???b,,,#c";
char *t;
t = strtok(str, "?"); // t points to the token "a"

这篇关于当第一个标记为空时需要 strtok 函数的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆