c++primer 2/28---string

来源:互联网 发布:java获取字符串编码 编辑:程序博客网 时间:2024/05/18 01:48

当进行 string 对象和字符串字面值混合连接操作时,+ 操作符的左右操作数必须至少有一个是 string 类型的:

     string s1 = "hello";   // no punctuation     string s2 = "world";     string s3 = s1 + ", ";           // ok: adding a string and a literal     string s4 = "hello" + ", ";      // error: no string operand     string s5 = s1 + ", " + "world"; // ok: each + has string operand     string s6 = "hello" + ", " + s2; // error: can't add string literals

 s4 的初始化试图将两个字符串字面值相加,因此是非法的。s6 的初始化是非法的。依次来看每个子表达式,则第一个子表达式试图把两个字符串字面值连接起来。

虽然任何整型数值都可作为索引,但索引的实际数据类型却是类型 unsigned 类型 string::size_type


sizeof("hello")=6,"hello"是字符串字面值,这是C风格字符串,末尾自动添加结束符\0,sizeof()包含结束符,。strlen();不包含结束符的长度。

string s("hello");s.size=5.是用字符串字面值(包含结束符)为c++类型的字符串对象初始化,初始化的对象中不包含结束符(生成对象的时候自动滤掉了)。并不是s.size()没有把结束符算进来。


Null characters were needed in C 

In c++ you can forget '\0' if you use string class, you just don't need to worry about it.

Null characters were needed in C because if you did something like
char myText[] = "HELLO";
myText would really be a pointer to somewhere in memory, let's say forexample, it's at memory location 100 (which it probably wouldn't be butthat's a nice round number), the memory might really look like
100: HELLO\0askdj7y3hcdm,chy3nc73hjkcz78zxcojczxkj
Without that \0 (null character) there, C wouldn't know whether the string was H, HELLO, HELLOaskdj or anything else.

However, in C++ "strings" are no longer null-terminated because thestring object can store not only what characters make up the string (asC did), but how long it should be, so a C++ string can just say "HELLO"is 5 characters, so start at the pointer and read 5 characters.

原创粉丝点击