![]() |
VOOZH | about |
In C++, we usually represent text data using the std::string object. But in some cases, we may need to convert a std::string to a character array, the traditional C-style strings. In this article, we will learn how to convert the string to char array in C++.
Examples
Input: str = "geeksforgeeks"
Output: char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', '\0' };
Explanation: str is converted to character array.Input: str = "abc"
Output: char arr[] = {'a', 'b', 'c', '\0'}
Explanation: str is converted to character array.
Following are the different ways to convert the string to char array in C++:
To change std::string to char array, we can first use string::c_str() function to get the underlying character array that contains the string stored in std::string object. Then we can create a copy of this char array using strcpy() function. We can also use & (Address-of) operator to get the underlying character array by fetching the address of the first character.
{ g, e, e, k, s, f, o, r, g, e, e, k, s, }Time complexity: O(n), where n is the number of characters in a string.
Auxiliary Space: O(n)
In the above method, we have first fetched the underlying character array of std::string object. But we can also directly convert std::string to char array by using std::copy() function. This function works for both iterators and pointers so we can copy the std::string objects (uses iterator) directly to character array (uses pointers).
copy(first, last, pos);
Parameters
{ g, e, e, k, s, f, o, r, g, e, e, k, s, }Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n)
To manually covert the string to char array, we can use any C++ loop to iterate through each element of the std::string and copy the character to the char array one by one.
{ g, e, e, k, s, f, o, r, g, e, e, k, s, }Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n)