Convert Array to String in C++

Convert Array to String in C++ (5 Programs).

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}

Output

Array: Hello
String (method 1): Hello
String (method 2): Hello
String (method 3): Hello

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

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.
1#include <sstream>

Displaying Results

The program prints:

Output:

Array: Hello

String (method 1): Hello

String (method 2): Hello

String (method 3): Hello

All three methods produce the same string "Hello".

1cout << "Array: " << arr << endl;
2cout << "String (method 1): " << str1 << endl;
3cout << "String (method 2): " << str2 << endl;
4cout << "String (method 3): " << str3 << endl;

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];

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

1// ... fill buffer from C function

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.