1. 程式人生 > >C++ string split函式實現

C++ string split函式實現

使用了string的find函式和substr函式

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<string> split(string str, string pattern) {
    vector<string> result;
    str += pattern;
    for (int i = 0; i < str.size(); i++) {
        int pos = (int
)str.find(pattern, i); if (pos != string::npos) { result.push_back(str.substr(i, pos - i)); i = pos + (int)pattern.size() - 1; } } return result; } int main() { string s = "I have a dream!"; vector<string> res = split(s, " "); return
0; }