How can we convert one string to char array in Modern C++? Here are the answers with C++ software examples.
Generally, as an introduction to C++, in addition to int, float, double there is another data type, string that we use for alphanumeric variables. In C++ there are several typedefs for common character types are provided: String types are defined in header <string>.
strings are the string class for byte characters represented with string and alphanumeric characters are stored and displayed in string forms. In another terms string stores for the alphanumeric text with 1 byte chars, called ASCII chars. Strings are the instantiation of the basic_string class template that uses char as the character type. Simply we can define a string as below,
1 2 3 |
std::string str = "This is a String"; |
string has methods to assign, copy, align, replace or to operate with other strings. These methods can be used in all string methods with their appropriate syntax. Here are the string types defined in std namespace with their char type and C++ standard.
How do I convert a String to a Char array in C++?
We can convert a string to a char array as below;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> int main() { std::string s1 = "This is a String"; char s[255] = ""; s1.copy( s, s1.length() ); std::cout << s1 << std::endl; std::cout << s << std::endl; getchar(); return 0; } |
and the string and char array outputs will be,
1 2 3 4 |
This is a String This is a String |
Another method is using c_str() property of std::string. We can copy this to with strcpy() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> int main() { std::string s1 = "LearnCPlusPlus.org"; char s[255] = ""; strcpy(s, s1.c_str()); std::cout << s << std::endl; getchar(); return 0; } |
and the char array output will be,
1 2 3 |
LearnCPlusPlus.org |