将 std::wstring 拆分为 std::vector [英] Splitting std::wstring into std::vector
问题描述
这个问题展示了如何使用单个字符分隔符将string
分割成vector
.
This question shows how to split a string
into a vector
using a single character delimeter.
然而,将这种技术应用于 wstring
并不像我想象的那么容易.因此这绝对不是重复的!
However, applying this technique to wstring
isn't as easy as I thought. Therefore this is definitely not a duplicate at all!
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, ";"));
第二行不能用VS2015编译.并且使用 istream_iterator
会导致 iterator.h
中的编译错误.
The second line can't be compiled using VS2015. And using istream_iterator<wstring, wchar_t>
causes a compile error in iterator.h
.
如何将 std::wstring
拆分为由 ";"
分隔的 std::vector
?
How can I split a std::wstring
into a std::vector
that is separated by ";"
?
推荐答案
您将无法使用示例中的方法.该方法依赖于以空格分隔的输入.在你的问题中,你说你的字符串 ;
像 "the;quick;brown;fox"
一样分隔.为此,您可以使用 std:getline
和 ';'
作为分隔符来拆分字符串.
You are not going to be able to use the method in your example. That method relies on the input being white space seperated. In your question you say your strings a ;
separated like "the;quick;brown;fox"
. In order to do that you can use std:getline
with ';'
as the delimiter to break up the 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);
以上将字符串加载到流中,然后将继续调用 std::getline
在 ';'
处中断,直到到达流的末尾.
The above loads the string into the stream and then will keep calling std::getline
breaking at the ';'
's until it reaches the end of stream.
我还想指出,如果您的第二个示例将您不会看到的数据拆分为
I would also like to point out that had your second example split the data you would not have seen it as
copy(List.begin(), List.end(), ostream_iterator<wstring>(cout, ";"));
将把';'回到字符串中.当您处理宽字符时,它还需要 std::wcout
而不是 std::cout
.
Will put the ';' right back into the string. It also needs std::wcout
instead of std::cout
as you are dealing with wide characters.
根据 cppreference ctype
有两个不同的char
和 wchar_t
的特化并且具有不同的功能.你不能只用 ctype
改变 ctype
的所有出现,并且因为 ctype
缺少函数而完成第二个例子使用
According to cppreference ctype
has two different specializations for char
and wchar_t
and the have different function. You cannot just change all occurances of ctype<char>
with ctype<wchar_t>
and be done as ctype<wchar_t>
is missing functions that the second example uses
这篇关于将 std::wstring 拆分为 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!