2

I'm about to hit the screen with my keyboard as I couldn't convert a char to a string, or simply adding a char to a string.

I have an char array and I want to pick whichever chars I choose in the array to create a string. How do I do that?

string test = "oh my F**king GOD!"
const char* charArray = test.c_str();

string myWord = charArray[0] + charArray[4];

thats how far I got with it. Please help.

1
  • 1
    Or you could do string myWord; myWord += charArray[0]; myWord += charArray[4]; Cat PlusPlus's way is better, I'm just saying that you can use concatenation for that too. Commented Nov 4, 2011 at 16:46

4 Answers 4

5
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);

You don't need to use c_str() here.

Sign up to request clarification or add additional context in comments.

2 Comments

There is also basic_string& operator=(charT c). I think I would use that. Like, myWord += test[0].
@Alf: Missed a + in the function declaration?
1

no need to convert to c_str just:

string test = "oh my F**king GOD!";
string myWord;
myWord += test[0];
myWord += test[4];

Comments

0

Are you restricted in some way to use C++ functions only? Because, for this purpose I use the old C functions like sprintf

1 Comment

To all passers-by: Please take the direct opposite of this advice! Quite conversely, you should [generally] use C functions only when you are restricted to them for some legacy reason.
0

You need to also need to remember that a C++ string is quite similar to a vector, while a C string is just array of chars. Vectors have an operator[] and a push_back method. Read more here You use push_back and do not convert to c string. So your code would look like this:

string test = "oh my F**king GOD!"
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);

1 Comment

A C++ string is not a vector. A vector is a vector; a string is a string. And it's operator[].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.