將字符串綁定到輸入流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中包含的分割字符時,則會將該字符改為\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());