【问题标题】:Why does string size not change if I add an additional character in it?如果我在其中添加一个附加字符,为什么字符串大小不会改变?
【发布时间】:2018-12-04 07:57:17
【问题描述】:

在下面的程序中,当我向字符串添加一个字符时,它的大小仍然保持不变(从 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

【问题讨论】:

  • 当我在字符串中再添加一个字符时 -- 你在哪里做呢?您的程序中没有“添加字符”。
  • 这种误解正是为什么教 C++ 的人不应该从 C 开始的原因。从intstd::stringstd::vector 开始教 C++ 并完成任务。向量或字符串的实际外观以及如何在 C++ 中使用 C 的东西很有趣,但更高级。 std::vector&lt;std::string&gt; args(argv + 1, argv + argc); 应该是最早教授的语句之一,因此练习可以包括基本的参数处理。

标签: c++ string c++11


【解决方案1】:

Operaton str1[5] = 'a'; 不会向字符串“添加”某些内容;它将值设置在特定位置,并且该位置必须在0..(length()-1) 范围内;否则,行为未定义。

要将某些内容附加到字符串,请使用

str1 += "a";

str1.push_back('a');

请注意,std::string - 与普通的“C”风格字符串相比 - 在单独的属性中维护 length(并且不计算它纯粹依赖于字符串终止字符 '\0')。

【讨论】:

  • size() 函数如何计算字符串的长度(这里我们看到它不是 NULL 终止的,在我做 str1[5] = 'a'; 之后)
  • 值得指出的是,当字符串的值为“hello”(其长度为 5)时,为 str1[5] 赋值是未定义的行为。不保证尾随 0 存储在包含实际字符串字符的字符数组中,因此对索引 5 的写入超出范围。如果您使用at() 而不是operator[],则该字符串应引发异常。
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
相关资源
最近更新 更多