How to Convert a std::string to char* in C++?
Last Updated :
14 Feb, 2024
In C++, strings are the textual data that is represented in two ways: std::string which is an object, and char* is a pointer to a character. In this article, we will learn how to convert a std::string to char* in C++.
Example
Input:
string myString = "GeeksforGeeks";
Output:
char * myString = "GeeksforGeeks";
Convert std::string to char* in C++
The std::string is also implemented using char array so it is very easy and straightforward to perform this conversion. To convert a std::string to a char*, we can use the std::string:c_str() method that returns a pointer to a null-terminated character array (a C-style string).
C++ Program to Convert std::string to char*
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString = "Geeks For Geeks" ;
cout << "string: " << myString << endl;
const char * charPointer = myString.c_str();
cout << "C-style string: " << charPointer << endl;
return 0;
}
|
Output
string: Geeks For Geeks
C-style string: Geeks For Geeks
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...