先学Python后学其他语言的后遗症就是Python中很多好用的方法在别的语言中都找不到
所以自己写一个吧
1 #include "stdafx.h" 2 #include <iostream> 3 #include <list> 4 5 void stringSplit(std::string msg, std::string part, std::list<std::string> &result) 6 { 7 int msgLen = msg.length(); 8 int partLen = part.length(); 9 int offset = 0; 10 std::string ele = ""; 11 std::cout << "msg length:" << msgLen << "part length:" << partLen << std::endl; 12 while (offset < msgLen) 13 { 14 int stop = offset + partLen; 15 std::string piece = msg.substr(offset, partLen); 16 cout << "piece is " << piece << " offset is " << offset << " stop is " << stop << endl; 17 if (piece == part) 18 { 19 result.push_back(ele); 20 offset = offset + partLen; 21 ele = ""; 22 } 23 else 24 { 25 ele = ele + msg[offset]; 26 offset++; 27 } 28 } 29 result.push_back(ele); 30 } 31 32 // limit 准备分割的次数, 如,2,代表函数发现两次分隔符,就会停止,返回长度为3的列表 33 void stringSplit(std::string msg, std::string part, std::list<std::string> &result, int limit) 34 { 35 int msgLen = msg.length(); 36 int partLen = part.length(); 37 int offset = 0; 38 std::string ele = ""; 39 std::cout << "msg length:" << msgLen << "part length:" << partLen << std::endl; 40 int sign = 0; 41 while (offset < msgLen) 42 { 43 int stop = offset + partLen; 44 std::string piece = msg.substr(offset, partLen); 45 cout << "piece is " << piece << " offset is " << offset << " stop is " << stop << endl; 46 if (piece == part) 47 { 48 result.push_back(ele); 49 offset = offset + partLen; 50 ele = ""; 51 sign++; 52 if (sign == limit){ 53 result.push_back(msg.substr(offset, msgLen - offset)); 54 return; 55 } 56 } 57 else 58 { 59 ele = ele + msg[offset]; 60 offset++; 61 } 62 } 63 result.push_back(ele); 64 }
对字符串进行一次遍历,每次切取与分隔符等长的一段,如果与分隔符一致,则将前一段字符串放入result,否则,当前位置往后移动一次