std::string 字符串切割

在很多字符串类库里都实现了split函数。不过在std里没有实现。在这里拿出几个:

1. 用单字符作为分隔

 1 #include <string>
 2 #include <vector>
 3 using namespace std;
 4  
 5 vector<string> split(string strtem,char a)
 6 {
 7         vector<string> strvec;
 8  
 9         string::size_type pos1, pos2;
10         pos2 = strtem.find(a);
11         pos1 = 0;
12         while (string::npos != pos2)
13         {
14                 strvec.push_back(strtem.substr(pos1, pos2 - pos1));
15  
16                 pos1 = pos2 + 1;
17                 pos2 = strtem.find(a, pos1);
18         }
19         strvec.push_back(strtem.substr(pos1));
20         return strvec;
21 }

2. 由多个分隔符来分隔:

 1 std::vector<std::string> splitString(std::string srcStr, std::string delimStr, bool repeatedCharIgnored)
 2 {
 3     std::vector<std::string> resultStringVector;
 4     std::replace_if(srcStr.begin(), srcStr.end(),
 5         [&](const char& c){if (delimStr.find(c) != std::string::npos){ return true; } else{ return false; }}/*pred*/, delimStr.at(0));
 6     //将出现的所有分隔符都替换成为一个相同的字符(分隔符字符串的第一个)
 7     size_t pos = srcStr.find(delimStr.at(0));
 8     std::string addedString = "";
 9     while (pos != std::string::npos) {
10         addedString = srcStr.substr(0, pos);
11         if (!addedString.empty() || !repeatedCharIgnored) {
12             resultStringVector.push_back(addedString);
13         }
14         srcStr.erase(srcStr.begin(), srcStr.begin() + pos + 1);
15         pos = srcStr.find(delimStr.at(0));
16     }
17     addedString = srcStr;
18     if (!addedString.empty() || !repeatedCharIgnored) {
19         resultStringVector.push_back(addedString);
20     }
21     return resultStringVector;
22 }

 

posted @ 2018-07-27 14:17  漆天初晓  阅读(6600)  评论(0编辑  收藏  举报