一边遍历一边分割:
<span style="white-space:pre"> </span>// split -> vector std::vector<Point> points; std::string lo = "2,1 2,2 2,4 4,3 "; for (int p1 = 0, p2 = 0; (p2 = lo.find(" ", p1 + 1)) >= 0; p1 = p2) { std::string sub = lo.substr(p1, p2); { int x = 0; int y = 0; sscanf(sub.c_str(), "%d,%d", &x, &y); points.push_back( Point(x,y) ); } };
方法1:
char str[] = "a,b,c,d*e"; const char * seprator = ","; char * p = strtok(str, seprator); while (p) { CCLOG("%s\n", p); p = strtok(NULL, seprator); }
void strSplit(std::string str, const char* seprator, std::vector<std::string>& strs_out); void SceneBattleField::strSplit(std::string str, const char* seprator, std::vector<std::string>& strs_out) { int pos = 0; int pos_start = 0; int seplen = strlen(seprator); do { pos = str.find(seprator, pos_start); if (pos > 0) strs_out.push_back(str.substr(pos_start, pos - pos_start)); else strs_out.push_back(str.substr(pos_start)); pos_start = pos + seplen; } while (pos > 0); }
std::string strSplitAt(std::string str, const char* seprator, int index); // 字符串分割,直接获取某个分割位上的字符。index从0开始 std::string strSplitAt(std::string str, const char* seprator, int index) { std::string strRet = ""; int pos = 0; int pos_start = 0; int seplen = strlen(seprator); int i = 0; do { pos = str.find(seprator, pos_start); if (i == index) { if (pos > 0) strRet = str.substr(pos_start, pos - pos_start); else strRet = str.substr(pos_start); } pos_start = pos + seplen; i++; } while (pos > 0); return strRet; }
调用例子:
char * str = "a,*b,*c,*d*e"; std::vector<std::string> strs; strSplit(str, ",*", strs); std::string str2 = strSplitAt(str, ",*", 0);
[0] 0x9bf21c
[1] 0x9bf55c