最近筆試,經常遇到需要對字符串進行快速分割的情景,主要是在處理輸入的時候,而以前練習算法題或筆試,很多時候不用花啥時間考慮測試用例輸入的問題。可是C++標准庫里面沒有像java的String類中提供的字符分割函數split ,着實不方便。那么怎么解決這個問題呢?整理了一些方法如下:
1.簡潔高效的方法(不過只能包含一個分隔符):
#include <vector>
#include <string>
#include <iostream>
using namespace std;
void SplitString(const string& s, vector<string>& v, const string& c)
{
string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
v.push_back(s.substr(pos1));
}
int main(){
string s = "a,b,c,d,e,f";
vector<string> v;
SplitString(s, v,","); //可按多個字符來分隔;
for(vector<string>::size_type i = 0; i != v.size(); ++i)
cout << v[i] << " ";
cout << endl;
//輸出: a b c d e f
}
當處理有空格的字符串時,還是很有用的!!
使用void SplitString(const string& s, vector<string>& v, const string& c),和將v作為返回值都是可以的!
2.可包含多個分隔符的實現方式
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<string> split(const string &s, const string &seperator){
vector<string> result;
typedef string::size_type string_size;
string_size i = 0;
while(i != s.size()){
//找到字符串中首個不等於分隔符的字母;
int flag = 0;
while(i != s.size() && flag == 0){
flag = 1;
for(string_size x = 0; x < seperator.size(); ++x)
if(s[i] == seperator[x]){
++i;
flag = 0;
break;
}
}
//找到又一個分隔符,將兩個分隔符之間的字符串取出;
flag = 0;
string_size j = i;
while(j != s.size() && flag == 0){
for(string_size x = 0; x < seperator.size(); ++x)
if(s[j] == seperator[x]){
flag = 1;
break;
}
if(flag == 0)
++j;
}
if(i != j){
result.push_back(s.substr(i, j-i));
i = j;
}
}
return result;
}
int main(){
// string s = "a,b*c*d,e";
string s;
getline(cin,s);
vector<string> v = split(s, ",*"); //可按多個字符來分隔;
for(vector<string>::size_type i = 0; i != v.size(); ++i)
cout << v[i] << " ";
cout << endl;
//輸出: a b c d e
}
方法三:用C語言中的strtok 函數來進行分割
原型: char *strtok(char *str, const char *delim);strtok函數包含在頭文件<string.h>中,對於字符數組可以采用這種方法處理。
#include <string.h>
#include <stdio.h>
int main(){
char s[] = "a,b*c,d";
const char *sep = ",*"; //可按多個字符來分割
char *p;
p = strtok(s, sep);
while(p){
printf("%s ", p);
p = strtok(NULL, sep);
}
printf("\n");
return 0;
}
//輸出: a b c d
