在下面的程序中,当我在字符串中再添加一个字符时,其大小仍然保持不变(从str1.size()函数可以明显看出)。为什么会这样?
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
int main() {
std::string str1 = "hello";
cout << "std::string str1 = \"hello\""<< endl;
cout << "string is " << str1 << " with length " << str1.size() << endl;
str1[5] = 'a';
cout << "string is " << str1 << " with length " << str1.size() << endl;
for (int i = 0 ; i < 7; i++) {
cout << "str["<<i<<"] = " << str1[i] << " (int)(str[i])" << (int)str1[i] << endl;
}
}
输出
std::string str1 = "hello"
string is hello with length 5
string is hello with length 5 //expected 6
str[0] = h (int)(str[i])104
str[1] = e (int)(str[i])101
str[2] = l (int)(str[i])108
str[3] = l (int)(str[i])108
str[4] = o (int)(str[i])111
str[5] = a (int)(str[i])97
str[6] = (int)(str[i])0
答案 0 :(得分:6)
操作符str1[5] = 'a';
不会将某些内容“添加”到字符串中。它将值设置在特定位置,并且该位置必须在0..(length()-1)
范围内;否则,行为是不确定的。
要在字符串后附加内容,请使用
str1 += "a";
或
str1.push_back('a');
请注意,与普通的“ C”样式字符串相反,std::string
将length
保留在单独的属性中(并且不仅仅依靠字符串终止符{{1 }}。