C++标准库的string不是以'\0'结束,而是string类中有一个记录长度的值
(具体怎么实现我不是很清楚,要等看过STL代码或者比我牛的大牛来给你说)
但是C++中的string你要得到它有多长,可以这么做
string str("abc");
str.size();
str.length(); //都返回3
而且,str中不会以'\0'判断字符串结束,可以这样
string str2("\0\0\0\0\0");
str2.size(); //等于5
如果要用string返回一个C style string
那么可以
str.c_str(); //会在字符串内容后加上一个C style string 的结束符号'\0' 这里返回的就是 "abc\0"
str.data(); //这里返回的是 "abc"
嗯,我错了,但是我在看书的时候怎么是这么写的
我找找看
C++ Standard Library : A tutorial and Reference
中11.1章
Unlike C-strings, objects of class string have no special character '\0' at the end of the string.
Note that only the single-argument version char* handles the character '\0' as a special character that terminates the string. In all other cases '\0' is not a special character:
std::string s1("nico"); //initializes s1 with: 'n' 'i' 'c' 'o'
std::string s2("nico",5) ; //initializes s2 with: 'n' 'i' 'c' 'o' '\0'
std::string s3(5,'\0'); //initializes s3 with: '\0' '\0' '\0' '\0' '\0'
s1.length() //yields 4
s2.length() //yields 5
s3.length() //yields 5
噢~~~ 是我错了,想这样初始化就对了~
std::string s3(5,'\0'); 这样s3 就是 "\0\0\0\0\0"
我那样初始化的确是错的,而且我大概知道错在哪里了~ 想想看~
想好了再跟个贴
C/C++ code
-
嗯,错在初始化方法相关
string
str(
"
\0\0\0
"
);
这里调用的是
string
(
const
char
*
p) 这个构造函数
这个构造函数的实现应该是依赖C style string的,我大概用自己的想法描述下
string
::
string
(
const
char
*
p)
{
/*
将string内部的char* mp申请一个p指向的C风格字符串的长度的空间
将p的内容COPY到mp中
那么在第一步的时候就使用C风格字符串的判断长度方法,判断这个"\0\0\0"的长度是0
- - 所以这样的初始化得不到我想要的结果
*/
}
而
string
(
int
count,
char
ch) 则能得到想要表达STL的string不把
'
\0
'
做特殊字符处理的意思