Convert a single character to a string?

C++Character

C++ 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++

  1. Using std::stringstream

    std::string str="abc",r; std::stringstream s; s<>r; std::cout<

  2. Using string ( size_t n, char c ); constructor

    std::string str="abc"; string r(1, str[0]);

  3. 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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMLPView Question on Stackoverflow
Solution 1 - C++SeanView Answer on Stackoverflow
Solution 2 - C++Michael BurrView Answer on Stackoverflow
Solution 3 - C++Prasoon SauravView Answer on Stackoverflow
Solution 4 - C++Peiti LiView Answer on Stackoverflow
Solution 5 - C++Jesse DhillonView Answer on Stackoverflow
Solution 6 - C++Sean RogersView Answer on Stackoverflow
Solution 7 - C++PuppyView Answer on Stackoverflow
Solution 8 - C++ARAVIND MANDIGAView Answer on Stackoverflow
Solution 9 - C++Mandeep singhView Answer on Stackoverflow