VOOZH about

URL: https://www.geeksforgeeks.org/cpp/convert-string-char-array-cpp/

⇱ Convert String to Char Array in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert String to Char Array in C++

Last Updated : 11 Jan, 2025

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++:

Using std::string::c_str() Method

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.

Code Implementation


Output
{ 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)

Using std::copy() Method

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).

Syntax

copy(first, last, pos);

Parameters

  • first: Iterator to the beginning of string object.
  • last: Iterator to the position just after the end of the string object.
  • pos: Pointer to the start of the character array

Code Implementation


Output
{ 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)

Using Loops

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.

Code Implementation


Output
{ 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)

Comment