zoukankan      html  css  js  c++  java
  • C++ split分割字符串函数

    将字符串绑定到输入流istringstream,然后使用getline的第三个参数,自定义使用什么符号进行分割就可以了。

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <vector>
    using namespace std;
    void split(const string& s,vector<int>& sv,const char flag = ' ') {
        sv.clear();
        istringstream iss(s);
        string temp;
    
        while (getline(iss, temp, flag)) {
            sv.push_back(stoi(temp));
        }
        return;
    }
    
    int main() {
        string s("123:456:7");
        vector<int> sv;
        split(s, sv, ':');
        for (const auto& s : sv) {
            cout << s << endl;
        }
        system("pause");
        return 0;
    }

     2、使用strtok函数。

           strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针

    #include<iostream>
    #include<cstring>
    using namespace std;
    int main()
    {
        char sentence[]="This is a sentence with 7 tokens";
        cout << "The string to be tokenized is:
    " << sentence << "
    
    The tokens are:
    
    ";
        char *tokenPtr=strtok(sentence," ");//sentence必须是一个char数组,不能是定义成指针形式
        while(tokenPtr!=NULL) {
            cout<<tokenPtr<<'
    ';
            tokenPtr=strtok(NULL," ");
        }
        //cout << "After strtok,sentence=" << tokenPtr<<endl;
        return 0;
    }

    //对于string s;
    //char tar[10000];
    //strcpy(tar,s.c_str());
  • 相关阅读:
    第四次作业
    第三周
    作业
    第一周学习计划
    小组作业进度(只做了大概还未加内容)
    第六次作业
    第五次作业
    第四次作业
    复习心得 JAVA异常处理
    预习心得
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/8228390.html
Copyright © 2011-2022 走看看