Site icon Learn C++

How To Convert A String to a Wide String In A Modern C++ App

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,

[crayon-67428320bb52e398246691/]

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,

[crayon-67428320bb53b495520410/]

and the Wide String output will be,

[crayon-67428320bb53c883067540/]

that means we successfully copied a string to a wide string.

Exit mobile version