C ++:仅使用STL从String中提取标记

时间:2012-06-04 03:40:10

标签: c++ string token

我想从给定的分数表达式中提取标记,该表达式以字符串形式传递,

Fraction s("-5 * 7/27");

如果提取的标记仅包含单个运算符或数字序列作为操作数,则仅使用stl容器。

有人可以指导我这样做吗?我想知道如何提取令牌并将操作数与运算符区分开来,谢谢。

1 个答案:

答案 0 :(得分:3)

假设令牌之间总是有空格,这就是如何将它们全部放入队列中:

#include <string>
#include <queue>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    stringstream formula("-5 * 7/27");
    string a_token;
    queue<string> tokens; 

    // Use getline to extract the tokens, and then push them onto the queue.
    while (getline(formula, a_token, ' ')) {
         tokens.push( a_token );
    }

    // Print and pop each token.
    while (tokens.empty() == false) {
        cout << tokens.front() << endl;
        tokens.pop();
    }
}

运行程序将输出:

-5
*
7/27

现在要确定哪些是运算符,数字或分数,你可以在循环中执行类似的操作:

    if (a_token == "+" || a_token == "-" || a_token == "*" || a_token == "/")
    {
        // It's an operator
        cout << "Operator: " << a_token << endl;
    }
    else
    {
        // Else it's a number or a fraction.

        // Now try find a slash '/'.
        size_t slash_pos = a_token.find('/');

        // If we found one, it's a fraction.
        if (slash_pos != string::npos) {
            // So break it into A / B parts.

            // From the start to before the slash.
            string A = a_token.substr(0, slash_pos);

            // From after the slash to the end.
            string B = a_token.substr(slash_pos + 1);

            cout << "Fraction: " << A << " over " << B << endl;
        }
        else
        {
            // Else it's just a number, not a fraction.
            cout << "Number: " << a_token << endl;
        }
    }

本网站:http://www.cplusplus.com/reference/string/string/将为您提供有关字符串功能的信息。

修改代码并再次运行后,您将获得如下输出:

Number: -5
Operator: *
Fraction: 7 over 27