#include #include #include #include #include #include int solution(char *str) { static const size_t LEN = 3; static const char* one = "one"; static const char* two = "two"; int operand[2] = {0, 0}; int operand_index = 0; char op = 0x00; char* ptr = str; while (*ptr != '\0') { int cmp = strncmp(ptr, one, LEN); if (cmp == 0) { operand[operand_index++] = 1; ptr += LEN; } cmp = strncmp(ptr, two, LEN); if (cmp == 0) { operand[operand_index++] = 2; ptr += LEN; } if (operand_index == 2) { operand_index = 0; int a = operand[0]; int b = operand[1]; int res = 0; if (op == '+') res = a + b; else res = a - b; operand[operand_index++] = res; } if (*ptr == '+') { op = '+'; } else if (*ptr == '-') { op = '-'; } else { assert(true && "Invalid parsing!"); } ++ptr; } return operand[0]; } int main() { char* str = "one+two-one-one+two+one"; int ret = solution(str); printf("input: %s = %d\n", str, ret); return 0; }