繁体   English   中英

如何通过索引将值分配给C ++字符串索引

[英]How to assign value to a c++ string index by index

如何通过索引将值分配给c ++字符串索引。 我已经尝试过此代码,但这不会更改字符串的值。

#include <iostream.h>
#include <string>

void change(string & str)
{
    str[0] = '1';
    str[1] = '2';
    // str = "12" ; // it works but i want to assign value to each index separately. 
}
void main()
{
    string str;
    change(str);
    cout << str << endl; // expected "12"
}

您可以这样做,但是在您可以按索引分配字符之前,必须首先调整字符串的大小,以使这些索引有效。

str.resize(2);

首先,此代码甚至不会编译。 错误:

  1. <iostream.h>不是标准头。 仅使用<header>
  2. 使用using namespace std; 或在coutendl加上std::前缀。
  3. main必须返回int ,而不是void

然后字符串的大小仍然为零,因此更改str[0]str[1]是未定义的行为。

要修复它,请使用std::string::resize (size_t)设置其尺寸:

str.resize (2);

使用STL sstreamstringstreams使得它更进行追加和创建动态字符串容易。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

void change(stringstream *ss, char value) {
    *ss << value;
}

int main() {
    stringstream stream;
    stream << "test";

    change(&stream, 't');

    cout << stream.str() << endl; //Outputs 'testt'
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM