简体   繁体   中英

How to convert std:wstring to std::vector<wchar_t>

If

std::wstring word = L"xxxxxxx";

Then how to do the following conversion?

std::vector<wchar_t> chars = word;

Just initialize it with a pair of iterators:

std::vector<wchar_t> chars(word.begin(), word.end());

The above will not add the null terminator (but if the string contains one, it will be copied). If you want it, initialize the vector with a pair of pointers to the underlying string data instead:

std::vector<wchar_t> chars(word.c_str(), word.c_str() + word.size() + 1);

Remember to add 1 for the null terminator, otherwise the effect will be the same as in the first example.

There is a way to create it in one go including the null terminator by using the c_str() or data() from the wstring. (In C++11 these are both guaranteed to be null terminated), and then adding size()+1 for the end position, also guaranteed to be well-defined behaviour.

Thus:

std::vector<wchar_t> chars( word.c_str(), word.c_str() + word.size() + 1 );

(or use data() instead of c_str() but only C++11 onward )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM