Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a single character to a string?

Tags:

c++

character

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?

like image 432
MLP Avatar asked Jul 11 '10 09:07

MLP


People also ask

How do I convert a single character to a string in C++?

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.

Can a single character be a string in Java?

There is no special handling of single-character String literals (not even of the 0-letter String literal "" ).


2 Answers

Off the top of my head, if you're using STL then do this:

string firstLetter(1,str[0]); 
like image 94
Sean Avatar answered Oct 14 '22 11:10

Sean


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)); 
like image 22
Michael Burr Avatar answered Oct 14 '22 10:10

Michael Burr