Convert String to Array
Convert String To Array in C++ (5 Programs)
C++ Convert String to Array Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
int main() {
string str = "Hello";
// Method 1: Using c_str() and copying
char arr1[10];
strcpy(arr1, str.c_str());
// Method 2: Using vector of chars
vector<char> arr2(str.begin(), str.end());
// Method 3: Manual copying
char arr3[10];
for (int i = 0; i < str.length(); i++) {
arr3[i] = str[i];
}
arr3[str.length()] = '\0';
cout << "String: " << str << endl;
cout << "Array (method 1): " << arr1 << endl;
return 0;
}String: Hello Array (method 1): Hello
Understanding Convert String to Array
This program teaches you how to convert a C++ string into a character array (C-style string) in C++. This conversion is necessary when you need to work with C functions, legacy code, or when you require the fixed-size array format. Understanding different conversion methods helps you choose the appropriate approach based on your specific needs and safety requirements.
---
1. What This Program Does
The program converts a C++ string (like "Hello") into a character array (like {'H', 'e', 'l', 'l', 'o', '\0'}). C++ strings are dynamic and managed, while character arrays are fixed-size and require manual memory management. This conversion bridges the gap between modern C++ strings and C-style character arrays.
Example:
---
2. Header Files Used
---
3. Declaring Variables
The program declares:
string str = "Hello";
---
4. Method 1: Using c_str() and strcpy()
char arr1[10];
strcpy(arr1, str.c_str());
This is a common C-style method:
How it works:
Advantages:
Disadvantages:
---
5. Method 2: Using Vector
vector<char> arr2(str.begin(), str.end());
This method uses a C++ vector:
How it works:
Advantages:
Disadvantages:
Example:
vector<char> vec(str.begin(), str.end());
---
// Access: vec[0], vec[1], etc.
// Size: vec.size()6. Method 3: Manual Copying
char arr3[10];
for (int i = 0; i < str.length(); i++) {
arr3[i] = str[i];
}
arr3[str.length()] = '\0';
This method manually copies each character:
How it works:
Advantages:
Disadvantages:
---
7. Other Methods (Mentioned but not shown in code)
Method 4: Using copy() Algorithm
char arr4[10];
copy(str.begin(), str.end(), arr4);
arr4[str.length()] = '\0';
#include <algorithm>Method 5: Using string data() Method
char* arr5 = new char[str.length() + 1];
strcpy(arr5, str.data());
---
// Remember to delete[] arr5 when done8. Displaying Results
The program prints:
Output:
The array is printed as a C-string, which automatically stops at the null terminator.
---
cout << "String: " << str << endl;
cout << "Array (method 1): " << arr1 << endl;9. Important Considerations
Null Terminator
:
Buffer Size
:
Memory Management
:
---
10. When to Use Each Method
-
c_str() + strcpy()
: When you need a fixed-size C-style array and know the maximum size.
-
Vector
: When you need dynamic size or want automatic memory management (recommended).
-
Manual Copying
: When you need custom logic during copying or want to understand the process.
-
copy() Algorithm
: When you prefer STL algorithms and want clean code.
-
data() Method
: When you need direct access to string's internal buffer (advanced use).
Best Practice
: Use vector for most cases - it's safe and modern. Use fixed arrays only when size is known and fixed.
---
11. Safety Considerations
Buffer Overflow Prevention
:
Example with Safety Check
:
const int MAX_SIZE = 10;
if (str.length() < MAX_SIZE) {
strcpy(arr, str.c_str());
} else {
}
// Handle error - string too longModern Alternative
:
---
12. Accessing Array Elements
After conversion, access characters like a normal array:
char arr[10];
strcpy(arr, str.c_str());
char first = arr[0]; // 'H'
char second = arr[1]; // 'e'
// Iterate through array
for (int i = 0; arr[i] != '\0'; i++) {
cout << arr[i];
}
---
// Access individual characters13. return 0;
This ends the program successfully.
---
Summary
This program is essential for beginners learning how to work with both C++ strings and C-style character arrays, understanding memory management, and choosing the right approach 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 String to Array
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.