C++ split分割字符串函數

將字符串綁定到輸入流istringstream,而後使用getline的第三個參數,自定義使用什麼符號進行分割就能夠了。ios

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

 二、使用strtok函數。數組

       strtok()用來將字符串分割成一個個片斷。參數s指向欲分割的字符串,參數delim則爲分割字符串中包含的全部字符。當strtok()在參數s的字符串中發現參數delim中包含的分割字符時,則會將該字符改成\0 字符。在第一次調用時,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:\n" << sentence << "\n\nThe tokens are:\n\n";
    char *tokenPtr=strtok(sentence," ");//sentence必須是一個char數組,不能是定義成指針形式
    while(tokenPtr!=NULL) {
        cout<<tokenPtr<<'\n';
        tokenPtr=strtok(NULL," ");
    }
    //cout << "After strtok,sentence=" << tokenPtr<<endl;
    return 0;
}//對於string s;//char tar[10000];//strcpy(tar,s.c_str());
相關文章
相關標籤/搜索