如何在C++中将字符转换为字符串

How to convert char to string in C++?

本文关键字:字符 转换 字符串 C++      更新时间:2023-10-16

我有一个字符串变量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);