Select Page

How to Convert String to Char Array in C++

by | C++, Programming, Tips

A C++ string variable contains a collection of characters surrounded by double-quotes. There are two types of strings used in C++.

  • C-strings, which are arrays of type char terminated by the null character \0.
  • Strings that are objects of the Standard C++ Library string class.

This tutorial will go through how to convert strings to char arrays with the help of code examples.


Convert String to Char Array Using strcpy() and c_str()

We can convert a string object to const char * using the c_str() method.

However, we cannot edit the C-style string returned by c_str().

We pass the const char* to the strcpy() function, which copies it into the specified character array and returns a pointer to it.

Let’s look at an example. We take a string from the user, convert it to a char array and print it to the console.

#include <iostream>

using namespace std;

int main()
{

    string str = "";
    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    char arr[str.length() + 1];

    strcpy(arr, str.c_str());

    cout<<"String to char array conversion:\n";

    for (int i = 0; i < str.length(); i++)

        cout << arr[i];

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Convert String to Char Array Using std::copy

The above method uses C’s strcpy() method. The recommended C++ approach uses the std::copy function, which copies all elements in the range of the first and last string into the specified char array. We then add the terminating character ‘\0’ at the end of the char array. Let’s look at an example below:

#include <iostream>

using namespace std;

int main()
{

    string str = "";

    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    int len = str.size();

    char *c = new char[len + 1];

    std::copy(str.begin(), str.end(), c);
    
    c[len] = '\0';

    cout<<"String to char array conversion:\n";


    cout << c;

    delete[] c;

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Convert String to Char Array Using std::vector

We can convert the string to a vector of characters and then push the terminating character to the end of the vector. Then we can get a pointer to the underlying character array by using either &str[0] or &*str.begin(). Let’s look at an example below:

#include <iostream>
#include <vector>
using namespace std;

int main()
{

    string str = "";
    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    std::vector<char> chars(str.begin(), str.end());

    chars.push_back('\0');

    char *c = &chars[0];

    cout<<"String to char array conversion:\n";

    cout << c;

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Convert String to Char Array Using For Loop

We take an input string and use its length to define an empty char array in this approach. Then, we use a for loop to iterate over the string characters and set each element in the char array to the element at the same position in the string object. Let’s look at an example below:

#include <iostream>
#include <string>
using namespace std;

int main()
{

    string str = "";
    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    char c[str.length()];

    int i;

    cout<<"String to char array conversion:\n";

    for (i=0; i<sizeof(c); i++){
        c[i] = str[i];
        cout << c[i];
    }

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Convert String to Char Array Using a Pointer

This method is the most efficient approach because it does not involve copying. We can directly assign the address of the first character in the string object to a pointer to the underlying char array by using either &str[0] or &str.begin(). Any changes made to the char* will appear in the string object and vice versa. Let’s look at an example below:

#include <iostream>
#include <string>
using namespace std;

int main()
{

    string str = "";
    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    char* c = &str[0];

    cout<<"String to char array conversion:\n";

    cout << c;

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Convert String to Char Array Using cons_cast Operator

The const_cast operator removes the const attribute from a class. The string::c_str and string::data return const char*, which we then have to copy to a character array using strcpy(). If we use the const_cast operator, no copying is required, making this method work in constant time.

This approach gives us access to the underlying char array behind std::string, so any changes we make to the char* will manifest in the string object and vice versa. Let’s look at an example below:

#include <iostream>
#include <string>
using namespace std;

int main()
{

    string str = "";
    cout<<"Enter the string to convert to char array :\n";

    cin>>str;

    char* c = const_cast<char*>(str.c_str());

    cout<<"String to char array conversion:\n";

    cout << c;

    return 0;

}

Let’s run the code to get the result:

Enter the string to convert to char array :
Research
String to char array conversion:
Research

Summary

Congratulations on reading to the end of this tutorial. We have gone through the various ways to convert a string object to a char array in C++.

For further reading on string manipulation in C++, go to the articles:

Have fun and happy researching!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!