Converting a string to a character array is simple and straightforward, but before we jump to the solution, we need to identify a few built-in functions we would be using from the string library.
There are multiple ways of doing this, and the functions we will be using are copy, copy function from the algorithms header file, and strcpy from the cstring header file. Moreover, we can also convert a string to a char pointer which can be very useful when creating complex applications in C++.
Converting String to Char array
Let’s first do the most common way i.e. simply copying a string to a char array by using the equal to sign.
#include<iostream> using namespace std; int main() { // assigning value to string s string str = "Hello World"; // declaring character array char char_array[str.length()]; // traversing the string index by index // assigning values to character array for (int i = 0; i < sizeof(char_array); i++) { char_array[i] = str[i]; cout << char_array[i]; } return 0; }
Another more common approach uses the strcpy function, which is a built-in function and has the following prototype.
char* strcpy( char* dest, const char* src );
// The function copies the character string pointed to by the source to the memory location pointed to by destination.
The function is declaration is in the cstring header file, so we have to include that in our code, and the implementation is shown below.
#include <iostream> #include <cstring> using namespace std; //driver program int main() { string str = "Hello World!"; // char array of size string length + 1 to store null terminator as well char cstr[str.length() + 1]; // strcpy function copies string to cstr array strcpy(cstr, &str[0]); // printing the destination string cout << cstr; return 0; }
Strcpy behaves unpredictably if the destination memory is not large enough as required. Next comes the copy function that is present in the string library, and we can use this because strcpy is originally a function present in C, and the syntax is as follows.
source.copy(destination, length of source)
Now let’s use this in a program.
#include <iostream> #include <string> using namespace std; //driver program int main() { string s = "Hello World!"; int length = s.size() + 1; // creating an array of the length of the string // adding +1 to store the null terminator char cstr[length]; s.copy(cstr, length); // Adding a null character manually cstr[s.size()] = '\0'; cout << cstr << endl; return 0; }
There is another function called copy present in the algorithm header file and has the following syntax.
//specify starting and ending of the string to copy
// the last argument is the target to which the string will be copied
copy(iterator source_first, iterator source_end, iterator target_start);
Now let’s see the implementation of the following function.
#include <iostream> #include <algorithm> using namespace std; //driver program int main() { string s = "Hello World!"; // create character array of size + 1 char cstr[s.size() + 1]; // copy value from beginning to end copy(s.begin(), s.end(), cstr); // Placing the null terminator manually at the end of character array cstr[s.size()] = '\0'; std::cout << cstr << '\n'; return 0; }
Another approach is turning strings to a char pointer and can be used interchangeably with the char array.
Converting string to a char pointer
Often in big applications, we need to convert a string to a char pointer to perform some task. This can be done using the same functions (Strcpy, copy). However, there is another function called c_str() that returns const char pointer.
Let’s start with our first implementation using the c_str() function.
#include <iostream> #include <string> using namespace std; int main() { string str = "Hello World"; // using const_cast removes const attribute from the class char* c = const_cast<char*>(str.c_str()); cout << c; return 0; }
Similarly, we can use the above method of strcpy() to turn a string into a character pointer. The implementation of strcpy is demonstrated in the code below.
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string str = "Hello World"; /* create a character array of length + 1 c_str() is basic_string that contains a null-terminated sequence of characters representing the current value of basic_string object */ char* c = strcpy(new char[str.length() + 1], str.c_str()); cout << c; // delete pointer to free memory delete[] c; return 0; }
We can also use the copy function in the string library to convert string to a char pointer, and this idea is demonstrated in the code below.
#include <iostream> #include <string> using namespace std; int main() { string str = "I love C++"; //create a new character pointer of length + 1 char *c = new char[str.size() + 1]; // Take all the characters from start to end in str and copy it into the char pointer : c copy(str.begin(), str.end(), c); // add null character to the end of the character pointer c[str.size()] = '\0'; cout << c; // delete pointer to free memory delete[] c; return 0; }
Another method that can be used to achieve this task is memmove(). This function moves a block of memory by copying the values of num bytes of the source to the destination. The memmove function has the following syntax.
//Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
//Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
// Number of bytes that are to be copied
void * memmove ( void * destination, const void * source, size_t num );
Now that we are familiar with the syntax we move to the implementation using the memmove() function.
#include <iostream> #include <string> #include <cstring> using namespace std; int main(){ string str = "This will be converted to char*"; int length = str.length(); // create a character pointer char *c_string_copy = new char[ length + 1]; // content copied in c_string_copy memmove(c_string_copy, str.c_str(), length); /* do operations on c_string_copy here */ cout << c_string_copy; // delete character pointer delete [] c_string_copy; return 0; }
We can also use pointer manipulation to convert a string to a char pointer. This way of conversion is quite simple and easy.
#include <iostream> #include <string> using namespace std; int main() { string str = "This will be converted to char*\n"; // Assign the adress of str[0] to temp_ptr char *tmp_ptr = &str[0]; cout << tmp_ptr; // delete character pointer to free memory delete [] tmp_ptr; return 0; }
There is another way of implementing the above code using the begin function as shown below.
#include <iostream> #include <string> using namespace std; int main() { string str = "string to char*"; // &*str.begin() used in place of &str[0] char* c = &*str.begin(); cout << c; //delete pointer delete [] c; return 0; }
Moreover, we can also convert string to a vector of chars in contiguous memory, and then we can get the pointer to point to the character array. This approach is shown below.
#include <iostream> #include <string> #include <vector> using namespace std; int main() { string str = "Hello World"; // Can also str[0] in place of str.begin() vector<char> chars(str.begin(), str.end()); // add null character at the end of the char array chars.push_back('\0'); char *c = &chars[0]; cout << c; // delete pointer delete[] c; return 0; }
Conclusion
The whole article describes different ways a string can be converted to a character array. When developing applications, we can use this to manipulate strings and use it according to our requirements.