Convert Array to String

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

BeginnerTopic: String Conversion Programs
Back

C++ Convert Array to String Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <string>
using namespace std;

int main() {
    char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    // Method 1: Direct assignment
    string str1 = arr;
    
    // Method 2: Using string constructor
    string str2(arr);
    
    // Method 3: Using assign()
    string str3;
    str3.assign(arr);
    
    cout << "Array: " << arr << endl;
    cout << "String (method 1): " << str1 << endl;
    cout << "String (method 2): " << str2 << endl;
    cout << "String (method 3): " << str3 << endl;
    
    return 0;
}
Output
Array: Hello
String (method 1): Hello
String (method 2): Hello
String (method 3): Hello

Understanding Convert Array to String

This program teaches you how to convert a character array (C-style string) into a C++ string. This conversion is very common and usually straightforward because C++ strings can easily accept character arrays. Understanding different conversion methods helps you write clean, efficient code and handle various scenarios when working with legacy C code or character arrays.

---

1. What This Program Does

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"

---

2. 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.

---

3. 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.

---

4. 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"

---

5. 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

---

6. 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"

---

7. 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.

---

#include <sstream>

8. 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".

---

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

9. 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.

---

10. 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.

---

11. 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

// ... fill buffer from C function

Building Strings

:

string s = "Start";

char addition[] = "End";

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

---

12. 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

---

13. 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.

---

14. return 0;

This ends the program successfully.

---

Summary

Converting character arrays to strings is straightforward in C++.
Direct assignment is the simplest and most common method.
String constructor provides explicit construction option.
assign() is useful for replacing existing string content.
append() is useful for adding to existing strings.
Always ensure character arrays are null-terminated for safe conversion.
String creates its own copy - original array is not modified.
C++ strings are more convenient than character arrays for most use cases.

This program is essential for beginners learning how to work with both C-style character arrays and modern C++ strings, understanding the relationship between them, and choosing the right conversion method for different scenarios in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Convert Array to String

This C++ program is part of the "String Conversion Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents