在 c++ 中,std::string::size() 不计算修改后的字符串长度

In c++, std::string::size() does not count modified string length

本文关键字:计算 修改 字符串 c++ std string size      更新时间:2023-10-16

我的代码如下:

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;
}