How can I use copy() method of std::wstring in a C++ app? How can I copy a wide string to a wide char array? Here are the answers with C++ examples.
What is a WString?
wstrings (Wide Strings) are the string class for characters that has 2 bytes that represented with wstring. In Modern C++, alphanumeric characters are stored in wide strings because of their support for characters of World languages and displayed in wstring forms. In other words, wstring stores for the alphanumeric text with 2-byte chars, called wchar_t or WChar. Wide strings are the instantiation of the basic_string class template that uses wchar_t as the character type. Simply we can define a wstring as below,
1 2 3 |
std::wstring str = L"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. We can insert a wide string into another wide string in different methods. Let’s see some of most used methods.
How to copy a wide String to a Char Array using the copy() method of wstring
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::wstring s1 = L"This is a Wide String"; wchar_t s[255] = L""; s1.copy( s, s1.length() ); std::wcout << s1 << std::endl; std::wcout << s << std::endl; getchar(); return 0; } |
and the output will be,
1 2 3 4 |
This is a Wide String This is a Wide String |
How to copy a String to a Char array in a C++ app
We can copy a string to char array in given number of chars
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> int main() { std::wstring s1 = L"This is a Wide String"; wchar_t s[255] = L""; s1.copy( s, s1.length() ); std::wcout << s1 << std::endl; std::wcout << s << std::endl; getchar(); return 0; } |
and the output will be,
1 2 3 |
new string |
We can define number of characters to be copied as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> int main() { char s[] = ""; std::string s2 = "new string"; s2.copy(s, 5, 0); // copy 5 chars of s2 to s s[5] = 0; // set the next char 0 std::cout << s << '\n'; getchar(); return 0; } |
as you see we should set 0 the last character of the char array here. and the output will be,
1 2 3 |
new s |