views:

116

answers:

6

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?

+4  A: 

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));
Michael Burr
+1: the simplest and best ways
rubenvb
+4  A: 

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

string firstLetter(1,str[0]);
Sean
I used this and it works, thanks!
MLP
Note that `std::string` is not from that part of the standard library that was derived from the STL.
sbi
A: 

Here is the solution for both C and C++:

char* newStr = new char[1];
newStr[0] = str[0];
newStr[1] = '\0'
Mustafa Zengin
Needa to be an array of size 2, not 1.
Owen S.
`new char[1]` isn't going to get you very far in C, either.
Charles Bailey
@Owen S. don't be that much sure and give it a try.@Charles Bailey: you are definitely right, it's been a long time that I did not use C.
Mustafa Zengin
@Mustafa: Dude, you can see _right there_ that you're assigning two characters to a string that you've only allocated one byte of storage for. Its runtime behavior is undefined - it may work, it may crash, but it's entirely wrong either way. Run it through valgrind or a buffer overflow checker if you don't believe me.
Owen S.
+2  A: 

string firstletter(str.begin(), str.begin() + 1);

DeadMG
+4  A: 

1) Using 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

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

3) Using substr()

  string r(str.substr(0, 1));
Prasoon Saurav
A: 

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"
Jesse Dhillon