【问题标题】:Check if a string contains a string from index to another index检查字符串是否包含从索引到另一个索引的字符串
【发布时间】:2017-06-17 12:01:27
【问题描述】:

我尝试在 C++ 中做一个解释器,并且我想做一个函数,当用户输入 type(a) 时,它会给出变量 a 的类型,比如 a 是 int 或 bool 或 string。所以我的问题是我想知道前五个字母是否是类型(这是我认为为了做我想做的事情的最佳解决方案。但我的问题是如何以我在下面做的另一种方式做到这一点,因为这是一个非常丑陋的方式!

if (str.at(0) == 't' && str.at(1) == 'y' && str.at(2) == 'p' && str.at(3) == 'e' && str.at(4) == '(' )

【问题讨论】:

标签: c++ string


【解决方案1】:

您的问题的直接答案可能是使用std::string::comparestd::string::find;我想用“c++ string start with”这个词的谷歌搜索会直接给你带来优点和缺点的例子。

但是,当编写非常简单的解析器时,c 字符串库中的标记器strtok 可能是一种更简单的方法。 strtok 随后将字符串拆分为标记,其中对strtok 的每次调用都会返回下一个标记。分隔标记的字符作为参数传递给strtok

#include <iostream>
#include<stdio.h>
#include <stdlib.h>

int main()
{

    std::string str = "type(a)";

    if (str.compare(0,5,"type(") == 0) {
        // string starts exactly with `type(`;
        // note: 'type (' would not match...
    }

    char* analyzeStr = strdup(str.c_str());
    char *token = strtok(analyzeStr, "(");
    if (token && strncmp(token, "type", strlen("type")) == 0) {
        // command starts with "type(" or "type  ("
        token = strtok(NULL, ")");
        if (token) {
            // value between brackets
            printf("analyzing type of '%s'", token);
        }
    }
    free(analyzeStr);

    return 0;
}

【讨论】:

  • Read the documentation on strtok 使用前。它带有许多警告,这些警告源于旨在在更简单的时间内解决更简单的问题,并且可能不适合。例如注意需要char* analyzeStr = strdup(str.c_str());free(analyzeStr); 来绕过strtok 对源字符串的破坏性影响。
猜你喜欢
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
相关资源
最近更新 更多