C ++:将char插入字符串 [英] C++: insert char to a string

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

问题描述

所以我试图插入字符,我从一个字符串,到另一个字符串。
这里我的行为:
1.我想使用简单:

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。我收到一个错误,因为insert需要(在我的情况下)char *或字符串

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。一切似乎都成功编译,但程序崩溃的获取到

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

conversion >> myCharInsert;

行。

尝试用字符串替换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 ++:将char插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆