如何在 C++ 中将字符转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9347052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert char to string in C++?
提问by stressed_geek
I have a string variable s
, and I have a map data structure(with string keys) m
.
我有一个字符串变量s
,我有一个地图数据结构(带有字符串键)m
。
I want to check if each letter in s
is present in m
, so I do m.containsKey(s[i])
.
我想检查中的每个字母s
是否存在m
,所以我这样做了m.containsKey(s[i])
。
Since, map containsKey function expects string argument, I get the following error:
由于 map containsKey 函数需要字符串参数,因此出现以下错误:
invalid conversion from char to const char*
Any ideas, on how to convert a char to a string data-type?
关于如何将字符转换为字符串数据类型的任何想法?
回答by Ignacio Vazquez-Abrams
Take the substring instead of indexing.
取子串而不是索引。
s.substr(i, 1)
回答by Peiti Li
string s="";
char a;
s+=a;
s is now a string of char a
回答by ddacot
Another method is :
另一种方法是:
#include <sstream>
#include <string>
stringstream ss;
string s;
char c = 'a';
ss << c;
ss >> s;
回答by nijansen
You could do s.substr(i, 1)
. But if you have only char
s in your map, I like the answer above better.
你可以做s.substr(i, 1)
。但是如果你char
的地图中只有s,我更喜欢上面的答案。
回答by Krzysiek
string str = "test";
anyFunction(str[x]);
The [ ] operator provides you with a char and if any function expects string, then surely an error will occur. But you can always try this sneaky conversion:
[ ] 运算符为您提供一个字符,如果任何函数需要字符串,那么肯定会发生错误。但是您可以随时尝试这种偷偷摸摸的转换:
string str = "test";
char c = str[x];
string temp = c;
anyFunction(temp);