通常,我们会这样定义字符串并初始化:
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++爱好者少进陷阱,谢谢指正!