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++:将字符插入字符串
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
