This post will discuss how to create a character array from a string in C++.

1. Using std::string::copy

The standard solution to copy a sequence of characters from a string to a character array in C++ is with std::string::copy. Here’s how the code would look like:

Download  Run Code

Output:

Hello

 
Or dynamically create a character array of size n+1 for a string of length n and include null-terminating character to be safe, as shown below:

Download  Run Code

Output:

Hello

2. Using strcpy() function

The strcpy() function is used to copy the specified string to the destination buffer, including the null-terminating character. The buffer should be long enough to contain all characters of the C string and a null-terminating character.

This logic would translate to the following code. Since strcpy() function accepts a C string, the c_str() member function of std::string is used to get a C string from a C++ string.

Download  Run Code

Output:

Hello

 
Note that the strcpy() is a C function and should be avoided in C++. We can also dynamically create a character array of size n+1 for a string of length n, as shown below:

Download  Run Code

Output:

Hello

 
Alternatively, we can use the strncpy() function to copy all characters of the string to the destination buffer and null-terminate the string explicitly.

Download  Run Code

Output:

Hello

3. Using c_str() function

To get a null-terminated const array of characters representing the string content, we can directly use the c_str() function.

Download  Run Code

Output:

Hello

 
To get a char* instead of const char*, do like:

Download  Run Code

Output:

Hello

That’s all about creating a character array from a string in C++.