[英]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);
首先,此代码甚至不会编译。 错误:
<iostream.h>
不是标准头。 仅使用<header>
。 using namespace std;
或在cout
和endl
加上std::
前缀。 main
必须返回int
,而不是void
。 然后字符串的大小仍然为零,因此更改str[0]
和str[1]
是未定义的行为。
要修复它,请使用std::string::resize (size_t)
设置其尺寸:
str.resize (2);
使用STL sstream
为stringstreams
使得它更进行追加和创建动态字符串容易。
#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.