Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Convert Array to String in C++

Turn a null-terminated char array into a std::string in C++ with assignment, the constructor, or assign(). Explains why the '\0' at the end is required here.

BeginnerString Conversion ProgramsExample 11 of 11
convert-array-to-string.cpp
1#include <iostream>
2#include <string>
3using namespace std;
4
5int main() {
6 char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};
7
8 // Method 1: Direct assignment
9 string str1 = arr;
10
11 // Method 2: Using string constructor
12 string str2(arr);
13
14 // Method 3: Using assign()
15 string str3;
16 str3.assign(arr);
17
18 cout << "Array: " << arr << endl;
19 cout << "String (method 1): " << str1 << endl;
20 cout << "String (method 2): " << str2 << endl;
21 cout << "String (method 3): " << str3 << endl;
22
23 return 0;
24}

Sample Output

String (method 1): Hello

Copied up to the terminator.

In this one

  • How a char array with '\0' converts to a string
  • Three equivalent ways to do it
  • What goes wrong without the terminator
  • How to convert an array with a known length but no terminator

How it works

  1. 1

    arr holds H e l l o \0.

  2. 2

    str1 = arr copies until '\0'.

  3. 3

    str2(arr) does the same through the constructor.

  4. 4

    str3.assign(arr) does the same through a method.

  5. 5

    Print all four.

Edge cases

No terminator

Remove the '\0' from the initializer.

The conversion keeps reading past the array until it happens to hit a zero byte, which is undefined behavior. Use string(arr, 5) to give the length.

'\0' in the middle

Use {'H','i','\0','!','\0'}.

The conversion stops at the first '\0', so the string is just "Hi".

What's going on

The program converts a character array (like {'H', 'e', 'l', 'l', 'o', '\0'}) into a C++ string (like "Hello"). C++ strings are more convenient than character arrays because they automatically manage memory, provide length information, and offer many useful methods. This conversion allows you to use modern C++ string features with C-style data.

Example:

Input array: char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'}
Output string: "Hello"

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type and its methods.

Declaring Variables

The program declares:

char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};

char arr[] is a character array (C-style string).
Contains characters: 'H', 'e', 'l', 'l', 'o', and null terminator '\0'.
The null terminator ('\0') marks the end of the string.

Method 1: Direct Assignment

string str1 = arr;

This is the simplest and most common method:

C++ strings can be directly assigned from character arrays.
The string constructor automatically handles the conversion.
Copies the characters up to (but not including) the null terminator.

How it works:

When you assign a char array to a string, C++ automatically calls the string constructor.
The constructor reads characters until it finds the null terminator.
Creates a new string object with those characters.

Advantages:

Simplest syntax
Automatic and intuitive
Most commonly used method

Example:

char arr[] = "Hello";

string s = arr; // s = "Hello"

Method 2: Using String Constructor

string str2(arr);

This method explicitly uses the string constructor:

string(arr) calls the constructor that accepts const char*.
Same result as direct assignment but more explicit.
Makes it clear that construction is happening.

How it works:

The string constructor takes a pointer to the first character.
Reads characters until null terminator is found.
Creates a string object containing those characters.

Advantages:

Explicit about what's happening
Can be used in initialization lists
Clear intent

Example:

char arr[] = "Hello";

string s(arr); // Explicit construction

Method 3: Using assign()

string str3;

str3.assign(arr);

This method uses the assign() member function:

assign() is a string method that replaces the string's content.
Can be used on an existing string object.
Useful when you want to replace existing string content.

How it works:

1.Create an empty string: string str3;
2.Call assign() with the character array.
3.assign() copies characters from array to string.

Advantages:

Useful for replacing existing string content
Can assign to non-empty strings
Part of string's method set

Example:

string s = "Old";

char arr[] = "New";

s.assign(arr); // s now contains "New"

Other Methods (Mentioned but not shown in code)

Method 4: Using append()

string str4;

str4.append(arr);

append() adds the array contents to the string.
If string is empty, it's equivalent to assign().
Useful when building strings incrementally.

Example:

string s = "Prefix";

char arr[] = "Suffix";

s.append(arr); // s = "PrefixSuffix"

Method 5: Using stringstream

#include <sstream>

stringstream ss;

ss << arr;

string str5 = ss.str();

Uses stringstream to convert the array.
More complex but useful when combining multiple values.
Overkill for simple conversions.

Displaying Results

The program prints:

cout << "Array: " << arr << endl;

cout << "String (method 1): " << str1 << endl;

cout << "String (method 2): " << str2 << endl;

cout << "String (method 3): " << str3 << endl;

Output:

Array: Hello

String (method 1): Hello

String (method 2): Hello

String (method 3): Hello

All three methods produce the same string "Hello".

Important Considerations

Null Terminator:

Character arrays must end with '\0' for proper conversion.
String constructor reads until null terminator is found.
Without null terminator, it may read beyond array bounds (undefined behavior).

Array vs Pointer:

Both work: char arr[] and char* ptr.
String constructor accepts const char* (pointer to character).
Arrays automatically decay to pointers when passed to functions.

Memory Management:

String creates its own copy of the characters.
Original array is not modified.
String manages its own memory automatically.

When to Use Each Method

Direct Assignment: Best for most cases - simplest and most readable.
String Constructor: When you want explicit construction or using in initialization lists.
assign(): When replacing content of an existing string.
append(): When adding array content to existing string.
stringstream: When combining multiple values or complex formatting.

Best Practice: Use direct assignment for simple conversions - it's clean and efficient.

Common Use Cases

Reading from C Functions:

Many C functions return char*:

char* result = someCFunction();

string s = result; // Convert to C++ string

Working with Legacy Code:

When interfacing with C libraries:

char buffer[100];

// ... fill buffer from C function

string data = buffer; // Convert to modern C++ string

Building Strings:

string s = "Start";

char addition[] = "End";

s.append(addition); // s = "StartEnd"

Safety Considerations

Null Terminator Required:

Character array must be null-terminated.
Without it, string constructor may read invalid memory.

Example of Problem:

char arr[5] = {'H', 'e', 'l', 'l', 'o'}; // No null terminator!

string s = arr; // Undefined behavior - may read beyond array

Correct Way:

char arr[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // With null terminator

string s = arr; // Safe

Or Use String Literal:

char arr[] = "Hello"; // Automatically includes null terminator

string s = arr; // Safe

Performance Considerations

Copying:

String creates a copy of the array contents.
Original array is not affected.
Copying is usually fast for typical string sizes.

Memory:

String manages its own memory automatically.
No need to worry about memory leaks.
More convenient than manual char array management.

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What length is string("Hi\0there")?

Pick an answer to check it.

Question 2

How do you convert char a[3] = {'a','b','c'} safely?

Pick an answer to check it.

Questions people ask

Does the string share memory with the array?

No. The string makes its own copy.

What if I have a vector<char>?

string s(v.begin(), v.end());

Is char arr[] = "Hello" the same as the brace list?

Yes, the string literal form adds the '\0' automatically.