Simple question (in C++):
How do I convert a character into a string. So for example I have a 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++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
There is no special handling of single-character String literals (not even of the 0-letter String literal "" ).
Off the top of my head, if you're using STL then do this:
string firstLetter(1,str[0]);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With