Convert String to Array

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

IntermediateTopic: String Conversion Programs
Back

C++ Convert String to Array Program

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

Try This Code
#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;
}
Output
String: Hello
Array (method 1): Hello

Understanding Convert String to Array

This program demonstrates 5 different methods to convert a string to an array: using c_str() and strcpy(), using vector, manual copying, using copy() algorithm, and using string data() method.

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.

Table of Contents