C++中对字符串的分割方法

C++中对字符串的分割方法
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
#include <iostream>
#include <string>
#include <vector>
#include<algorithm>

using namespace std;
//字符串分割函数
vector<string> split(string str, string pattern)
{
    string::size_type pos;
    vector<string> result;

    str += pattern;//扩展字符串以方便操作
    int size = str.size();

    for (int i = 0; i<size; i++) {
        pos = str.find(pattern, i);
        if (pos<size) {
            std::string s = str.substr(i, pos - i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    return result;
}

int main(int argc, char** argv) {

    string str,pattern;
    vector<string> str_;
    cout << "Please input str:" << str << endl;
    cin >> str;
    cout << "Please input pattern:" << endl;
    cin >> pattern;
    str_ = split(str,pattern);

    for (int i = 0; i < str_.size(); i++) {
        cout << str_[i] << endl;
    }
    system("pause");
    return 0;
}

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18629

发表评论