C++ 将单个字符转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3222572/
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
Convert a single character to a string?
提问by MLP
Simple question (in C++):
简单的问题(在 C++ 中):
How do I convert a character into a string. So for example I have a string str = "abc";
如何将字符转换为字符串。例如,我有一个字符串 str = "abc";
And I want to extract the first letter, but I want it to be a string as opposed to a character.
我想提取第一个字母,但我希望它是一个字符串而不是一个字符。
I tried
我试过
string firstLetter = str[0] + "";
and
和
string firstLetter = & str[0];
Neither works. Ideas?
两者都不起作用。想法?
回答by Sean
Off the top of my head, if you're using STL then do this:
如果您使用的是 STL,请执行以下操作:
string firstLetter(1,str[0]);
回答by Michael Burr
You can use the std::string(size_t , char )
constructor:
您可以使用std::string(size_t , char )
构造函数:
string firstletter( 1, str[0]);
or you could use string::substr()
:
或者你可以使用string::substr()
:
string firstletter2( str.substr(0, 1));
回答by Prasoon Saurav
1) Using std::stringstream
1) 使用 std::stringstream
std::string str="abc",r;
std::stringstream s;
s<<str[0];
s>>r;
std::cout<<r;
2) Using string ( size_t n, char c );
constructor
2) 使用 string ( size_t n, char c );
constructor
std::string str="abc";
string r(1, str[0]);
3) Using substr()
3) 使用 substr()
string r(str.substr(0, 1));
回答by Jesse Dhillon
Use string::substr
.
使用string::substr
.
In the example below, f
will be the string containing 1 characters after offset 0 in foo
(in other words, the first character).
在下面的示例中,f
将是在偏移量 0 之后包含 1 个字符的字符串foo
(即第一个字符)。
string foo = "foo";
string f = foo.substr(0, 1);
cout << foo << endl; // "foo"
cout << f << endl; // "f"
回答by Sean Rogers
char characterVariable = 'z';
string cToS(1, characterVariable);
//cToS is now a string with the value of "z"
回答by Peiti Li
string s;
char a='c';
s+=a; //now s is "c"
or
或者
char a='c';
string s(a); //now s is "c"
回答by Puppy
string firstletter(str.begin(), str.begin() + 1);
字符串首字母(str.begin(), str.begin() + 1);
回答by ARAVIND MANDIGA
you can try this it works
你可以试试这个它有效
string s="hello";
string s1="";
s1=s1+s[0];