前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >C++中对字符串的分割

C++中对字符串的分割

作者头像
用户7886150
修改2021-01-18 11:46:51
修改2021-01-18 11:46:51
2.3K0
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: C++ find()查找子字符串

由于C++中没有split函数,因此,为了能够对获取的字符串进行按一定符号进行分割,在此学习了通过字符串的find()方法和substr()方法来实现split();具体描述如下:  //涉及到string类的两个函数find和substr:  //  //1、find函数  //原型: size_t find(const string& str, size_t pos = 0) const;  //功能: 查找子字符串第一次出现的位置。  //参数说明:str为子字符串,pos为初始查找位置。  //返回值: 找到的话返回第一次出现的位置,否则返回string::npos  //2、substr函数  //原型: string substr(size_t pos = 0, size_t n = npos) const;  //功能: 获得子字符串。  //参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)  //返回值: 子字符串 

#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;

运行结果如下所示:

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档