【问题标题】:What is the difference between following two string cases以下两个字符串案例有什么区别
【发布时间】:2021-12-15 03:41:09
【问题描述】:

我正在尝试将值分配给字符串然后访问它,但是对于第一种情况,我没有得到想要的输出......

#include <iostream>
#include <string>
using namespace std;
 
int main(){
      
      string abc;

      abc[0] = 'm';

      cout << "str1 : " << abc    << endl;
      cout << "str1 : " << abc[0] << endl;

      //-----------------------------------

      string xyz;

      xyz = "village";

      cout << "str2 : " << xyz    << endl;
      cout << "str2 : " << xyz[0] << endl;

      return 0;
}

输出应该是:

str1 : m
str1 : m
str2 : 村庄
str2 : v

但实际上是这样的:

str1 :
str1 : m
str2 : 村庄
str2 : v

【问题讨论】:

  • 如果你想使用std::string 和下标(operator[]),你必须事先确保字符串有足够的长度(无论你打算读还是写)。 std::string::resize() 是实现这一目标的一种方法。如果您想切断字符串的其余部分,则可以使用erase()resize()。请注意,std::string 在内部管理其存储。每当插入或删除某些内容时,都会在必要时调整存储空间,但覆盖单个字符不会改变长度。
  • 当你使用虚假代码时,询问“有什么区别”会消失。

标签: c++ arrays string char


【解决方案1】:

您的程序中存在错误,如下所述。

错误

string abc; //this creates a **0 sized** default constructed string object
abc[0] = 'm';// incorrect because you're trying to assign to the 0th index of the string object abc but note that there is no 0th index because the string has 0 size.

注意声明

abc[0] = 'm';

不正确,因为此时字符串对象 abc 的大小为 0,并且您正在尝试访问第一个元素(具有第 0 个索引)。但是等等,你怎么能访问一个没有任何元素的字符串的第一个元素(或第 0 个索引),因为它的大小为 0。

解决方案 1

您可以使用 abc 附加到字符串 abc 而不是分配给第 0 个索引

abc += 'm';

解决方案 2

您还可以创建具有特定大小(长度)和元素的std::string,如下所示:

std::string abc(1, 'm'); //now abc has size(length) of 1 and has the element(0th element) as "m".

有了这个,你就不需要使用你正在做的作业了。现在你不需要 abc[0] = 'm';

【讨论】:

    【解决方案2】:

    在第一种情况下,您正在用m 替换null-终止符(每个字符串都在末尾,以标记结束),并且可能会导致大量随机输出,如果不是SIGSEG 崩溃和/ 或未定义的行为。

    解决方案

    数组样式

    std::string myVariable;
    
    // ...
    
    myVariable.resize(3, '\x0');
    myVariable[0] = 'm';
    myVariable[1] = 'a';
    myVariable[2] = 'x';
    // And index 3 is already null-terminator (no need to set manually to zero).
    

    你应该怎么做

    如果速度不是问题,而您只想要稳定性和易用性,请尝试以下方法:

    abc += 'm';
    

    abc.append(1, 'm');
    
    

    【讨论】:

    • 有什么解决办法?
    • 如果我只想以这种方式分配和访问......
    • @AdityaVaste 如果您希望能够像数组一样设置和/或使用std::string,请参阅how to reserve memory(并且永远不要使用比您提前保留的索引更高的索引)。
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 2021-03-20
    • 2019-09-12
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多