Problem: We are given a string and asked to convert it into a char array in C++.

This problem can be solved in 4 ways:

1. String to char Array using ‘for loop’

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

Output

String to char array C++

2. String to char Array using strcpy()

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

Output

String to char array C++

3. String to Char Array using copy()

In this approach we are using std::copy() method to copy the all charaters of string to the array. It is important to append ‘\0’ to the array after the copy operation to end the char array.

Output

String to char array C++

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

In this last approach we are using inbuilt string library string::copy() method to copy string charaters to char array. The copy process is similar to std::copy().

Output

String to char array C++

Any Doubts? Comment Below.

Leave a Reply

Close Menu