有时需要把字符串按照字符进行分割为几个字符串,方法如下:
调用函数
void SplitString(const std::string& sSrc, const std::string& sSeparator, std::vector<std::string>& vecSub)
{
std::string::size_type posSubstringStart = 0;
std::string::size_type posSeparator = sSrc.find(sSeparator);
while (std::string::npos != posSeparator)
{
vecSub.push_back(sSrc.substr(posSubstringStart, posSeparator - posSubstringStart));
posSubstringStart = posSeparator + sSeparator.size();
posSeparator = sSrc.find(sSeparator, posSubstringStart);
}
vecSub.push_back(sSrc.substr(posSubstringStart));
}
说明
输入参数 sSrc:被进行分割的字符串
输入参数 sSeparator:要进行分割的分割符号
输出参数 vecSub:结果
注意:
分割符号前后的字符都会推进vector,即使是空字符
Test1
int main()
{
std::string szTest = "1|2|3|4";
std::vector<std::string> vecTest;
SplitString(szTest, "|", vecTest);
for (auto iter : vecTest)
{
std::cout << "Param: "<<iter<<std::endl;
}
system("pause");
}
Test1 result
Test2
int main()
{
std::string szTest = "1|2|3|4|";
std::vector<std::string> vecTest;
SplitString(szTest, "|", vecTest);
for (auto iter : vecTest)
{
std::cout << "Param: "<<iter<<std::endl;
}
system("pause");
}
Test2 result