Convert a single character to a string?
C++CharacterC++ Problem Overview
Simple question (in C++):
How do I convert a single character into a string.
So for example, I have string 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?
C++ Solutions
Solution 1 - C++
Off the top of my head, if you're using STL then do this:
string firstLetter(1,str[0]);
Solution 2 - C++
You can use the std::string(size_t , char )
constructor:
string firstletter( 1, str[0]);
or you could use string::substr()
:
string firstletter2( str.substr(0, 1));
Solution 3 - C++
-
Using
std::stringstream
std::string str="abc",r; std::stringstream s; s<
>r; std::cout< -
Using
string ( size_t n, char c );
constructor
std::string str="abc"; string r(1, str[0]);
-
Using
substr()
string r(str.substr(0, 1));
Solution 4 - C++
string s;
char a='c';
s+=a; //now s is "c"
or
char a='c';
string s(1, a); //now s is "c"
Solution 5 - C++
Use 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).
string foo = "foo";
string f = foo.substr(0, 1);
cout << foo << endl; // "foo"
cout << f << endl; // "f"
Solution 6 - C++
char characterVariable = 'z';
string cToS(1, characterVariable);
//cToS is now a string with the value of "z"
Solution 7 - C++
string firstletter(str.begin(), str.begin() + 1);
Solution 8 - C++
you can try this it works
string s="hello";
string s1="";
s1=s1+s[0];
Solution 9 - C++
If you want to return a string, there 2 ways to do this is given below:
1.`return (string) "" + S[i];
2.string s.push_back(originals[k];return s;