如何在C++中将字符转换为字符串
How to convert char to string in C++?
我有一个字符串变量s
,还有一个映射数据结构(带字符串键)m
。
我想检查s
中的每个字母是否都存在于m
中,所以我要检查m.containsKey(s[i])
。
由于map containsKey函数需要字符串参数,我得到以下错误:
invalid conversion from char to const char*
关于如何将字符转换为字符串数据类型,有什么想法吗?
使用子字符串而不是索引。
s.substr(i, 1)
string s="";
char a;
s+=a;
s is now a string of char a
另一种方法是:
#include <sstream>
#include <string>
stringstream ss;
string s;
char c = 'a';
ss << c;
ss >> s;
您可以执行s.substr(i, 1)
。但如果你的地图上只有char
,我更喜欢上面的答案。
string str = "test";
anyFunction(str[x]);
[]运算符为您提供了一个char,如果任何函数需要字符串,那么肯定会发生错误。但你总是可以尝试这种偷偷摸摸的转换:
string str = "test";
char c = str[x];
string temp = c;
anyFunction(temp);
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错