检查字符串是否包含从索引到另一个索引的字符串

Check if a string contains a string from index to another index

本文关键字:索引 字符串 另一个 是否 包含 检查      更新时间:2023-10-16

我试图用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) == '(' )

问题的直接答案可能是使用std::string::comparestd::string::find;我想,如果在谷歌上搜索"c++字符串开头",你会直接看到有优点和缺点的例子。

然而,在编写非常简单的解析器时,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;
}