Splitting std :: wstring into std :: vector

This question shows how to split a string into vector using a single character divider .

Question: The correct way to split std :: string into a vector

However, applying this technique to wstring not as easy as I thought. Therefore, this is certainly not a duplicate.

 wstringstream stringStream(str); istream_iterator<wstring> begin(stringStream); istream_iterator<wstring> end; List = vector<wstring>(begin, end); copy(List.begin(), List.end(), ostream_iterator<wstring>(cout, ";")); 

The second line cannot be compiled using VS2015. And using istream_iterator<wstring, wchar_t> causes a compilation error in iterator.h .

How can I split std::wstring into std::vector , which is split by ";" ?

+6
source share
1 answer

You cannot use this method in your example. This method is based on the fact that the input is free space. In your question, you say your lines are a ; separated as "the;quick;brown;fox" . For this you can use std:getline with ';' as a delimiter to break a string.

 std::wstring str = L"the;quick;brown;fox", temp; std::vector<std::wstring> parts; std::wstringstream wss(str); while(std::getline(wss, temp, L';')) parts.push_back(temp); 

The above loads the string into the stream, and then will call std::getline when split into ';' until it reaches the end of the stream.

I would also like to point out that if your second example shared data that you would not see in it

 copy(List.begin(), List.end(), ostream_iterator<wstring>(cout, ";")); 

Put ';' straight to the line. It also requires std::wcout instead of std::cout , since you are dealing with wide characters.

According to cppreference, ctype has two different specializations for char and wchar_t and they have different functions. You cannot just change all ctype<char> events to ctype<wchar_t> and run as ctype<wchar_t> no functions that the second example uses

+6
source

All Articles