通常这个任务是用基于所谓的有限状态机的词法解析器来解决的。
string s = "-2+-3+(4+5)";
List<string> tokens = new List<string>();
const int ST_NONE = 0, ST_MINUS = 1, ST_DIGITS = 2, ST_PUNCT = 3;
int j = 0; // token start
int st = ST_NONE; // state
for(int i = 0; i < s.Length(); ++i) {
switch(s[i]) {
case '0' .. '9':
if (st != ST_NONE && st != ST_DIGITS) { // any prev token
tokens.Add(s.SubStr(j, i - j)); // yield prev token
j = i; // start of new token
}
st = ST_DIGITS; // note transition from ST_MINUS
break;
case '-': // special case since number can start with it
if (st == ST_DIGITS) { // "4-" is definitely means "4 - .."
tokens.Add(s.SubStr(j, i - j)); // yield prev number
j = i, st = ST_PUNCT;
}
else if (st != ST_NONE) {
tokens.Add(s.SubStr(j, i - j)); // yield prev token
j = i, st = ST_MINUS;
}
else {
j = i, st = ST_MINUS;
}
break;
case '+': case '*': case '/': case '(': case ')':
if (st != ST_NONE) { // any prev token
tokens.Add(s.SubStr(j, i - j)); // yield prev token
j = i;
}
st = ST_PUNCT;
break;
default:
throw new UnexpectedCharacter();
}
}
if (st != ST_NONE) { // any prev token
tokens.Add(s.SubStr(j, i - j)); // yield prev token
}