在一些比较流行的语言中,字符串分割是一个比较重要的方法,不管是在python,java这样的系统级语言仍是js这样的前端脚本都会在用到字符串的分割,然而在c++中却没有这样的方法用来调用。可是在boost中却提供分割方法。前端
下面是用vector实现的一个简单的split函数,借助string::find函数查找匹配子串的位置,而后截取剩下的字符串以后继续处理,实现对原字符串的完整处理。java
#include<iostream> #include<vector> #include<string> using namespace std; vector<string> split(string &s, string &delim, bool removeEmpty = false, bool fullMatch = false) { vector<string> result; string::size_type start = 0, skip = 1; // 使用整个字符串进行查找,以后会直接跳过整个子字符串 if (fullMatch) { skip = delim.length(); } while (start != string::npos) { // 从start位置开始查找子字符串delim第一次出现的位置 string::size_type finsh = s.find(delim, start); if (skip == 0) { finsh = string::npos; } // 从start开始到(finsh - start)处得到子字符串 // 得到匹配字符串以前的字符串 string token = s.substr(start, finsh - start); // 对token进行判断并决定是否移除空 if (!(removeEmpty && token.empty())) { // 将匹配字符串以前的字符串放进向量中 result.push_back(token); } // 判断此时是否到了原字符串的末尾 if ((start = finsh) != string::npos) { // 将子字符串放进向量中,是为了保证原字符串的字符不丢失 result.push_back(delim); // 将查找位置向前移动skip个位置 start = start + skip; } } return result; } int main() { string x = "hello,,world", delim = ","; vector<string> xx = split(x, delim, true, true); for (auto item:xx) { cout << item << endl; } cout << "finsh" << endl; return 0; }