How to use .data() (with C++17 or newer) In C++
Using .data() to access a non-const char* of the std::string is the best option in C++17 or newer. Note: This can’t be run in the w3wiki IDE because it doesn’t support C++17.
Example:
C++
// C++ program to convert string // to char array using .data() #include <iostream> #include <string> // Driver Code int main() { std::string s = "w3wiki" ; char * char_arr = s.data(); std::cout << char_arr; return 0; } |
Output
w3wiki
- Time complexity: O(n)
- Auxiliary Space: O(1)
Convert String to Char Array in C++
Here, we will build a C++ program to convert strings to char arrays. Many of us have encountered the error ‘cannot convert std::string to char[] or char* data type’ so let’s solve this using 5 different methods:
- Using c_str() with strcpy()
- Using c_str() without strcpy()
- Using for loop
- Using the address assignment of each other method
- Using data() (C++17 and newer)
Input:
string s = "w3wiki";
Output:
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', '\0' };