C++ How to Convert Char Array to String Easily
std::string constructor like std::string str(charArray); where charArray is your char array.Examples
How to Think About It
\0. The string constructor reads these letters until it finds this end marker and creates a string from them.Algorithm
Code
#include <iostream> #include <string> int main() { char charArray[] = "Hello C++"; std::string str(charArray); std::cout << str << std::endl; return 0; }
Dry Run
Let's trace converting charArray = "Hello C++" to string
Input char array
charArray = {'H','e','l','l','o',' ','C','+','+','\0'}
Create string from char array
std::string str(charArray) reads characters until '\0'
Output string
str = "Hello C++"
| Step | Character Read | String So Far |
|---|---|---|
| 1 | H | H |
| 2 | e | He |
| 3 | l | Hel |
| 4 | l | Hell |
| 5 | o | Hello |
| 6 | Hello | |
| 7 | C | Hello C |
| 8 | + | Hello C+ |
| 9 | + | Hello C++ |
| 10 | \0 | Stop reading |
Why This Works
Step 1: String constructor reads char array
The std::string constructor takes the char array and reads characters one by one.
Step 2: Stops at null character
It stops reading when it finds the null character \0, which marks the end of the char array.
Step 3: Creates string object
It then creates a string object containing all characters read before the null character.
Alternative Approaches
#include <iostream> #include <string> int main() { char charArray[] = "Example"; std::string str = charArray; std::cout << str << std::endl; return 0; }
#include <iostream> #include <string> int main() { char charArray[] = "Assign method"; std::string str; str.assign(charArray); std::cout << str << std::endl; return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The string constructor reads each character until it finds the null terminator, so it takes time proportional to the length of the char array.
Space Complexity
The string allocates memory to store all characters, so space used is proportional to the char array length.
Which Approach is Fastest?
Using the constructor or assignment operator both have similar performance since they do the same work internally.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::string constructor | O(n) | O(n) | Creating new string from char array |
| Assignment operator | O(n) | O(n) | Simple syntax for new string |
| std::string::assign() | O(n) | O(n) | Assigning to existing string |
\0 so the string knows where to stop.\0 in the char array causes undefined behavior when converting to string.