在 c++ 中,std::string::size() 不计算修改后的字符串长度
In c++, std::string::size() does not count modified string length
我的代码如下:
int main(){
string s = "abcd";
int length_of_string = s.size();
cout<<length_of_string<<endl;
s[length_of_string] = 'e';
s[length_of_string+1] = 'f';
int length_of_string2 = s.size();
cout<<length_of_string2<<endl;
return 0;
}
据我所知,每个字符串都以 NULL 字符结尾。在我的代码中,我声明了一个长度为 4 的字符串。然后我打印给出值为 4 的length_of_string。然后我修改它并添加两个字符,索引 4 处的"e"和索引 5 处的 'f'。现在我的字符串有 6 个字符。但是当我再次阅读它的长度时,它显示长度是 4,但我的字符串长度是 6。
在这种情况下,s.size(( 函数是如何工作的。直到空字符不是计数吗?
程序的行为未定义。
std::string
的长度由 size()
返回。
虽然允许您使用 []
在索引size()
之前修改字符串中的字符,但不允许在此日期或之后修改字符。
参考: http://en.cppreference.com/w/cpp/string/basic_string/operator_at
如果需要在字符串末尾推送一个字符,则应使用std::string::push_back
函数为:
int main(){
string s = "abcd";
int length_of_string = s.size();
cout<<length_of_string<<endl;
s.push_back('e');
s.push_back('f');
int length_of_string2 = s.size();
cout<<length_of_string2<<endl;
return 0;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- 独立读取-修改-写入顺序
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 如何计算数据类型的范围,例如int
- 在 c++ 中,std::string::size() 不计算修改后的字符串长度
- 将顶点缓冲区绑定到计算着色器以修改数据
- OpencCV:从修改后的直方图计算图像
- 如何修改svm.cpp来计算点和超平面之间的距离?(LIBSVM)