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++.
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:
Frequently Asked:
- Replace Last Character of a String in C++
- Check if Char Array contains a string in C++
- Compare a String and a char array in C++
- C++ : Check if a String starts with an another given String
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++.