簡體   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