检查字符串是否包含从索引到另一个索引的字符串
Check if a string contains a string from index to another index
我试图用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::compare
或std::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;
}
相关文章:
- 按字母顺序对C++问题中的子字符串索引进行分区
- C++ 中字符串向量的索引
- C++ - 成功打印超出范围的字符串索引
- 对于循环增量器不能用作字符串向量的索引
- 如何检索由带通配符的字符串索引的对象
- 访问包含P的有效索引时返回空格的C++字符串
- 在我的 for 循环中,如何将索引更改为字符串?
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- C++ 复制字符串的指定索引之间的任何子字符串
- 查找C++中两个索引之间的子字符串
- 具有二叉索引树的字符串查询
- 有效地从文本文件中读取带有字符串索引的大型二维数组(矩阵)
- 尝试查找从索引 0 开始的偶数长度子字符串
- 如何根据某个索引将字符串与正则表达式匹配?
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 通过字符串的字符对整数数组进行索引
- 从给定索引返回子字符字符串的函数
- 此代码如何启动索引为 1 的 C 样式字符串
- 如何使用二叉搜索返回姓氏(给定字符串)的第一个索引/出现次数?
- 索引c++字符串的最简单方法