29

所以我试图将我从一个字符串中得到的字符插入到另一个字符串中。在这里我我的行动: 1. 我想用简单的:

someString.insert(somePosition, myChar);

2. 我收到一个错误,因为插入需要(在我的情况下)char* 或字符串
3. 我正在通过 stringstream 将 char 转换为 char*:

stringstream conversion;
char* myCharInsert;
conversion << myChar //That is actually someAnotherString.at(someOtherPosition) if that matters;
conversion >> myCharInsert;
someString.insert(somePosition, myCharInsert);

4. 一切似乎都编译成功了,但是程序崩溃了

conversion >> myCharInsert;

线。

5.我正在尝试用字符串替换 char*:

stringstream conversion;
char* myCharInsert;
conversion << myChar //That is actually someAnotherString.at(someOtherPosition) if that matters;
conversion >> myCharInsert;
someString.insert(somePosition, myCharInsert);

一切似乎都很好,但是当someAnotherString.at(someOtherPosition)变成空间时,程序崩溃了。

那么我该如何正确地做到这一点呢?

4

4 回答 4

52

有许多重载std::string::insert。插入单个字符的重载实际上有三个参数:

string& insert(size_type pos, size_type n, char c);

The second parameter, n, is the number of times to insert c into the string at position pos (i.e., the number of times to repeat the character. If you only want to insert one instance of the character, simply pass it one, e.g.,

someString.insert(somePosition, 1, myChar);
于 2010-07-11T14:00:52.187 回答
3

Simplest is to provide yourself with a function that turns a character into a string. There are lots of ways of doing this, such as

string ToStr( char c ) {
   return string( 1, c );
}

Then you can simply say:

someString.insert(somePosition, ToStr(myChar) );

and use the function in other cases where you want a string but have a char.

于 2010-07-11T14:02:19.813 回答
1
  1. Everything seems to be compiling successfully, but program crashes the gets to
conversion >> myCharInsert;

The problem is that you are trying to dereference(access) myCharInsert(declared as a char* ) which is pointing to a random location in memory(which might not be inside the user's address space) and doing so is Undefined Behavior (crash on most implementations).

EDIT

To insert a char into a string use string& insert ( size_t pos1, size_t n, char c ); overload.

Extra

To convert char into a std::string read this answer

于 2010-07-11T14:02:18.420 回答
0

You can try:

std::string someString{"abc"};
someString.push_back('d');
于 2022-03-02T16:37:19.680 回答