C++:将字符插入字符串

C++: insert char to a string(C++:将字符插入字符串)

本文介绍了C++:将字符插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将我从一个字符串中得到的字符插入到另一个字符串中.这是我的行动:1.我想用simple:

so I am trying to insert the character, which i got from a string, to another string. Here I my actions: 1. I want to use simple:

someString.insert(somePosition, myChar);

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

2. I got an error, because insert requires(in my case) char* or string
3. I am converting char to char* via stringstream:

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

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

4. Everything seems to be compiling successfully, but program crashes the gets to

conversion >> myCharInsert;

行.

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

5.I am trying to replace char* with string:

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

似乎一切正常,但是当 someAnotherString.at(someOtherPosition) 变成空格时,程序崩溃了.

Everything seems to be OK, but when someAnotherString.at(someOtherPosition) becomes space, program crashes.

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

So how do I correctly do this?

推荐答案

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

There are a number of overloads of std::string::insert. The overload for inserting a single character actually has three parameters:

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

第二个参数nc插入到字符串pos位置的次数(即插入的次数重复该字符的次数.如果您只想插入一个字符实例,只需传递一个,例如,

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);

这篇关于C++:将字符插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++:将字符插入字符串

基础教程推荐