C++: insert char to a string(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);
第二个参数n是c插入到字符串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++:将字符插入字符串
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
