在很多字符串類庫里都實現了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 }