C++字符串陷阱

通常,我们会这样定义字符串并初始化:

char *str="string";

这样定义虽然能够快速的获取字符串元素值,但是这些字符串是存储在文字常量表中,不能被修改。如果使用指针修改值,将会抛出异常。下面上一段程序:

char* Strsep(char** stringp, const char* delim)
{
    char *begin, *end;

    begin = *stringp;
    if (begin == NULL)
        return NULL;

    /** A frequent case is when the delimiter string contains only one
    character.  Here we don't need to call the expensive `strpbrk'
    function and instead work using `strchr'.  */
    if (delim[0] == '\0' || delim[1] == '\0') {
        char ch = delim[0];

        if (ch == '\0')
            end = NULL;
        else {
            if (*begin == ch)
                end = begin;
            else if (*begin == '\0')
                end = NULL;
            else
                end = strchr(begin + 1, ch);//可以查找字符串s中首次出现字符c的位置
        }
    }
    else {
        /** Find the end of the token.  */
        end = strpbrk(begin, delim);//是在源字符串(s1)中找出最先含有搜索字符串(s2)中任一字符的位置并返回,若找不到则返回空指针
    }

    if (end) {
        /** Terminate the token and set *STRINGP past NUL character.  */
        *end++ = '\0';
        *stringp = end;
    }
    else {
        /** No more delimiters; this is the last token.  */
        *stringp = NULL;
    }
    return begin;
}

该程序的功能是获取字符串中被特殊符号分割的前一部本,并将前一部分从字符串中剔除掉。但是使用起来则需要注意字符串陷阱,特便是该函数中使用了这一句话:

*end++ = '\0';

这是对字符串进行赋值,那么需注意调用该函数时,应该以数组的形式进行声明,如下:

char str[]="-1,-1,-1,-1";

这样,常量字符串拷贝到栈中,可以进行修改值操作。亦可以使用下面的方法进行调用:

char *tmp="-1,-1,-1,-1";
char *str=_strdup(tmp);

将文字常量表中的字符串数据,拷贝的静态存储区中。
希望此文可以让C++爱好者少进陷阱,谢谢指正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值