Python有自带的字符串分割函数,但是C++却没有,于是参考网上各种C++分割字符串的资源,将其整理如下
方法1:
#include#include #include #include #include #include using namespace std; //字符串分割函数 vector split(string str, string pattern) { string::size_type pos; vector result; //扩展字符串以方便操作 str += pattern; int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { string s = str.substr(i, pos - i); result.push_back(s); i = pos + pattern.size() - 1; } } return result; } int main() { string str = "str1+str2+str3"; string pattern = "+"; vector result = split(str, pattern); for (int i = 0; i < result.size(); i++) { cout << result[i] << endl; } return 0; }
方法2:
#include#include #include #include #include using namespace std; //1、该函数会改变原字符串的值 //2、该函数会根据delimiter里边的每一个字符进行分割,而非把delimiter作为一个整体 //3、相较于strtok()函数,strtok_s函数需要用户传入一个指针,用于函数内部判断从哪里开始处理字符串,其他的使用与strtok()函数相同 int main() { //原始字符串 char string[] = "A,string*of/tokens and some more,tokens"; //分隔符 char delimiter[] = ",*/ "; //存储返回结果 char* result = NULL; //context没有过于的作用,只是一个参数而已 char* context = NULL; //返回切割的第一个结果 result = strtok_s(string, delimiter, &context); printf("[string]:%sn", string); while (result != NULL) { printf("[result]:%sn", result); result = strtok_s(NULL, delimiter, &context); } return 0; }
方法3:
#include#include #include using namespace std; void Tokenize(const string& str, vector & tokens, const string& delimiters) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } int main(int argc, char* argv[]) { string str("====aaa==bbb==ccc==ddd====eeee*****eeeee"); vector results; Tokenize(str, results, "=*"); for (int i = 0; i < results.size(); i++) { cout << results[i] << endl; } return 0; }



