Convert string to char array in C++

In this article, we will discuss different ways to convert a string to a char array in C++.

Table Of Contents

Method 1: Using string::copy()

Create an array of same length as string, and initialize it with null characters. Then use the copy() function of string object to copy all characters of string to the array. For that, pass the array as first argument to the string::copy() function, and pass the number of characters to be copied as second argument i.e. length of string in our case. It will copy all characters of string to the array. Let’s see an example,

#include <iostream>
#include <string>

int main()
{
    std::string sampleText = "This text needs to finalized";

    // create an array of same size as string
    char textArr[sampleText.size() + 1] = {'
#include <iostream>
#include <string>
int main()
{
std::string sampleText = "This text needs to finalized";
// create an array of same size as string
char textArr[sampleText.size() + 1] = {'\0'};
// Convert string to char array
sampleText.copy(textArr, sampleText.length());
std::cout << textArr << std::endl;
return 0;
}
'}; // Convert string to char array sampleText.copy(textArr, sampleText.length()); std::cout << textArr << std::endl; return 0; }

Output:

This text needs to finalized

It converted the string to a char array in C++.

Advertisements

Method 2: using strcpy()

Create an array of same length as string, and initialize it with null characters. Then use the strcpy() function to copy all characters of string to the array. Let’s see an example,

#include <iostream>
#include <string>
#include <cstring>

int main()
{
    std::string sampleText = "This text needs to finalized";

    // create an array of same size as string
    char textArr[sampleText.size() + 1] = {'
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::string sampleText = "This text needs to finalized";
// create an array of same size as string
char textArr[sampleText.size() + 1] = {'\0'};
// Convert string to char array
strcpy(textArr, sampleText.c_str());
std::cout << textArr << std::endl;
return 0;
}
'}; // Convert string to char array strcpy(textArr, sampleText.c_str()); std::cout << textArr << std::endl; return 0; }

Output:

This text needs to finalized

It converted the string to a char array in C++.

Summary

We learned how to convert a string to a char array in C++.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top