标签:代码 一个 ase hot start 输入 比较 iostream 其他
给定一个字符串,-是分隔符 --或更多的---是分隔符,除了字母和数字外,其他的都是分隔符,将字符串分隔
a--stu- he-ll0-go--od $@go-0d aaa
a stu he-ll0 go od go-0d aaa
题目要判断的条件比较多,用状态机做会清晰很多:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define WORD 0
#define ONE_SHOT 1
#define SPLIT 2
#define is_alpha(x) ((x>='a' && x<='z') || (x>='A'&&x<='Z') || (x>='0'&&x<='9'))
#define NEXT(str, i) ((i>=(str.size()-1)) ? 0 : str[i+1])
void split(string str, vector <string>& vec)
{
int state;
char next;
int start, end;
if(is_alpha(str[0])) {
state = WORD;
start = 0;
} else {
state = SPLIT;
}
for(int i=0; i<str.size();i++) {
next = NEXT(str, i);
switch(state) {
case WORD: {
if(next == 0) {
end = i;
vec.push_back(str.substr(start, end-start+1));
} else if(is_alpha(next)) {
state = WORD;
} else if(next == '-') {
state = ONE_SHOT;
end = i;
} else {
state = SPLIT;
end = i;
vec.push_back(str.substr(start, end-start+1));
}
break;
}
case ONE_SHOT: {
if(is_alpha(next)) {
state = WORD;
} else {
state = SPLIT;
vec.push_back(str.substr(start, end-start+1));
}
break;
}
case SPLIT: {
if(is_alpha(next)) {
state = WORD;
start = i+1;
} else {
state = SPLIT;
}
break;
}
}
}
return;
}
int main(int argc, char **argv)
{
string str1("*a--stu*- he-ll0*-go--od * $@go-0d aaa");
vector <string> vec;
split(str1, vec);
for(int i=0; i<vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
标签:代码 一个 ase hot start 输入 比较 iostream 其他
原文地址:https://www.cnblogs.com/joechow/p/12258295.html