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++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01