In this article, we are going to learn how to convert String to Char Array in C++. We are going to learn this with the help of multiple techniques.
- Using std::basic_string::c_str Method to Convert String to Char Array
- Using Pointer Manipulation Operations to Convert String to Char Array
1. Using std::basic_string::c_str Method to Convert String to Char Array
In this example, we are going to use the string class built-in function c_str() which gives us a null-terminated char array of the string.
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
string str = "Welcome to DevEnum.com tutorials";
const char* str2 = str.c_str();
cout << str2 << endl;
cout <<"\nThe type of str2 is: " << typeid(*str2).name() << endl;
return 0;
}
Output
Welcome to DevEnum.com tutorials
The type of str2 is: c
2. Using Pointer Manipulation Operations to Convert String to Char Array
In this example, we are making use of the pointers. We are assigning the starting index pointer to the char array. This will give the char pointer access to the whole string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Welcome to DevEnum.com tutorials";
char *strChar = &str[0];
cout <<"New string in Char array is: " <<strChar;
return 0;
}
Output
New string in Char array is: Welcome to DevEnum.com tutorials
Another method to do this is by using the memmove() function.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string str = "Welcome to DevEnum.com tutorials";
char *strChar = &str[0];
memmove(strChar, str.c_str(), str.length());
cout <<"New string in Char array is: " <<strChar;
return 0;
}
Output
New string in Char array is: Welcome to DevEnum.com tutorials