Problem: Convert a string into a Char array in C++.

There are 4 major ways using which we can convert a string to char array in C++.

Let’s discuss each of them.

1. String to char Array using ‘for loop’

Output

String to char array C++

In this approach, we are simply iterating through each character of the string value and assigning it to the corresponding index of the char array.

It is important to append '\0' to the end of the char array after the copy operation otherwise error will occur.

2. String to char Array using strcpy()

Output

String to char array C++

In this approach, we are first converting the ‘c++ string‘ into ‘c string‘ using c_str() method. Then we are copying the converted c-type string into the char array using strcpy() method.

3. String to Char Array using copy()

Output

String to char array C++

In this approach, we are using std::copy() method to copy all characters of the string into the char array.

4. String to Char Array using string::copy()

Output

String to char array C++

In this last approach, we are using inbuilt string library string::copy() method to copy string charaters to char array.

The string::copy() works similar to std::copy().

Using any of these 4 methods we can easily convert any string to a char array in C++.

Leave a Reply