分割字符串
Posted htj10
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分割字符串相关的知识,希望对你有一定的参考价值。
``` find() : Finds the first substring equal to the given character sequence find_first_of() : Finds the first character equal to one of characters in the given character sequence //字符串分割函数 str为待分割的字符串 pattern为任意分割符(**每一个字符都为分割符**),例如:";,"是以 ‘;‘ 和 ‘,‘ 分割,并且去掉了分割后的空字符串。 sbcssdfs 以s分割得 "bc" "df" vector<string> split(string str, string pattern) vector<string> ret; if (pattern.empty()) return ret; size_t start = 0; size_t index = str.find_first_of(pattern, 0); while (index != string::npos) if (start != index) ret.push_back(str.substr(start, index - start)); start = index + 1; index = str.find_first_of(pattern, start); if (!str.substr(start).empty()) ret.push_back(str.substr(start)); return ret; //分割后保留空字符串。sbcssdfs 以s分割得 "" "bc" "" "df" "" vector<string> split(string str, string pattern) vector<string> ret; if (pattern.empty()) return ret; size_t start = 0; size_t index = str.find_first_of(pattern, 0); while (index != string::npos) ret.push_back(str.substr(start, index - start)); start = index + 1; index = str.find_first_of(pattern, start); ret.push_back(str.substr(start)); return ret; ``` 用Poco中的StringTokenizer ``` #include "Poco/StringTokenizer.h" #include "Poco/String.h" // for cat // 分割字符串,s:将被分割的字符串,k:分割符 // 例如: k是 ";,"表示用 ‘;‘ 和 ‘,‘ 分割 std::vector<std::string> SplitString(std::string s, std::string k) /* Poco::StringTokenizer t1("red, green, blue", ","); // "red", " green", " blue" (note the whitespace) Poco::StringTokenizer t2("red,green,,blue", ","); // "red", "green", "", "blue" Poco::StringTokenizer t3("red ; green , blue", ",;", Poco::StringTokenizer::TOK_TRIM); // "red", "green", "blue" Poco::StringTokenizer t4("red; green,, blue", ",;", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); // "red", "green", "blue" std::string ss(Poco::cat(std::string("; "), t4.begin(), t4.end())); // "red; green; blue */ Poco::StringTokenizer st(s, k);//这样是不去掉 "" ,当加上 TOK_IGNORE_EMPTY(宏定义为1)即去掉 "" 了。 std::vector<std::string> vecRet(st.begin(), st.end()); return vecRet; ``` 另外一个字符串整体为分割符:(单个字符就跟上面的一样了) ``` //pattern作为一个整体当分割符,(不去掉 "") vector<string> split(string str, string pattern) vector<string> ret; if (pattern.empty()) return ret; size_t start = 0; size_t index = str.find(pattern, 0); while (index != string::npos) ret.push_back(str.substr(start, index - start)); start = index + pattern.size(); index = str.find(pattern, start); ret.push_back(str.substr(start)); return ret; ```
以上是关于分割字符串的主要内容,如果未能解决你的问题,请参考以下文章