How can I convert std::string to a std::wstring in a modern C++ app? How can I convert single byte string to 2-bytes wide string? Here are the answers with C++ examples.
In Modern C++, there are several typedefs for common character types are provided: Wide string types are defined in header <string>.
strings are the string class for byte characters represented with string. Alphanumeric characters are normally stored and displayed in string forms. The string class stores 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,
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 supports to characters of world languages and displayed in wstring forms. In another terms 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 4 |
std::string str = "This is a String"; std::wstring wstr = L"This is a Wide String"; |
The string class 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.
Converting a String to a Wide String in a C++ app
We can convert string (std::string) to a wstring (std::wstring) easily. To do this we should create a new wstring by using begin() and end() iterators of that string. Thus, this wstring will have same characters in that given range. See example below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string s1 = "This is a String"; std::wstring ws( s1.begin(), s1.end() ); // converting s1 to ws in its range std::wcout << ws << std::endl; getchar(); return 0; } |
and the Wide String output will be,
1 2 3 |
This is a String |
that means we successfully copied a string to a wide string.
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition