How to convert string to char array in C++
In this tutorial, we will learn how to convert a string into a character array in C++. There are multiple ways to convert a string to a char array in C++. Let’s discuss some of them here one by one.
Using for loop
We can easily convert a given C++ string into a character array by using for loop as shown in the below code.
#include <iostream>
#include <cstring>
using namespace std;
void print_char_array(char array[], int size)
{
for(int i=0; i<size; i++)
cout << array[i];
}
int main()
{
string s = "This is a string";
int size = s.length();
char array[size];
for(int i=0; i<size; i++)
{
array[i] = s[i];
}
print_char_array(array, size);
return 0;
}Output:
This is a string
Using strcpy() and c_str() functions
We can also use strcpy() and c_str() functions to convert a string into a character array in C++. The c_str() method returns a pointer to a null-terminated sequence of characters for a string object. We can copy these characters in our char array using strcpy() function. See the below example.
#include <iostream>
#include <cstring>
using namespace std;
void print_char_array(char array[], int size)
{
for(int i=0; i<size; i++)
cout << array[i];
}
int main()
{
string s = "This is a string";
int size = s.length();
char array[size + 1];
strcpy(array, s.c_str());
print_char_array(array, size);
return 0;
}Output:
This is a string
Using std::string::copy()
This method can also be used to convert a string to a char array. It takes two parameters – First, the character array to which we want to convert and the size of the string. The below program will help you understand it.
#include <iostream>
#include <cstring>
using namespace std;
void print_char_array(char array[], int size)
{
for(int i=0; i<size; i++)
cout << array[i];
}
int main()
{
string s = "This is a string";
int size = s.length();
char array[size + 1];
s.copy(array, size + 1);
print_char_array(array, size);
return 0;
}Output:
This is a string
By assigning the address of the string to a pointer to char
Another method to convert a string to char array is by assigning the address of the first character of the given string to a char pointer. Have a look at the following code.
#include <iostream>
#include <cstring>
using namespace std;
void print_char_array(char array[], int size)
{
for(int i=0; i<size; i++)
cout << array[i];
}
int main()
{
string s = "This is a string";
int size = s.length();
char *array;
array = &s[0];
print_char_array(array, size);
return 0;
}Output:
This is a string
Thank you.
You may also read: Find if a given sequence of characters are present in a parent string in C++
Leave a Reply