C++實現字符串分割有多種方式,個人認爲下面這種實現比較科學:
template<typename StrType>
void SplitString(const StrType& strSourceString, const StrType& strSeperator, std::vector<StrType>& vecResult)
{
StrType::size_type pos1 = 0, pos2 = strSourceString.find(strSeperator);
while (StrType::npos != pos2)
{
if (pos2 != pos1)
{
vecResult.push_back(s.substr(pos1, pos2 - pos1));
}
pos1 = pos2 + strSeperator.size();
pos2 = strSourceString.find(strSeperator, pos1);
}
if (pos1 != strSourceString.length())
{
vecResult.push_back(strSourceString.substr(pos1));
}
}
可根據需要生成std::string或std::wstring版本。