c++ - 表达式在使用指针时必须具有类类型
问题描述
我试图在 string1 中计算 string2 存在多少次。例如:string1 = abababd。字符串 2 = ab。结果:3。
(我必须为这个问题使用指针)
到目前为止我所拥有的:
int mystr(char* s, char* t) {
int counter = 0;
int length = strlen(t);
while (*s != '\0')
{
char d[] = *s.substr(0, 2);
if (*s == *t)
counter++;
*s += length;
}
return counter;
}
我一直收到这个问题:Expression must have class type for this line: char d[] = *s.substr(0, 2); 有人可以帮忙吗?
解决方案
substr
是类的方法std::string
。
您在此处使用 C 指针 ( char* s
),因此无需substr()
调用,因此出现错误。
当然,我会把实现留给你,但你可以通过 创建我自己的 substr来获得启发。
由于 OP 在尝试做自己的硬件方面表现出良好的信心,让我们评论一下到目前为止的方法:
int mystr(char* s, char* t) {
int counter = 0;
int length = strlen(t);
// while we haven't reach the end of string
while (*s != '\0')
{
// this is not used anywhere, and it's wrong. Why 2? You want the length of `t` there, if you would use it anyway
char d[] = *s.substr(0, 2);
// this is wrong. It will increase the counter,
// every time a character of the substring is matched with the
// current character in the string
if (*s == *t)
counter++;
// you want to read the next chunk of the string, seems good for a start
*s += length;
}
return counter;
}
所以现在,您应该专注于如何检查当前子字符串是否在字符串中匹配。所以,你需要改变这个:
if (*s == *t)
counter++;
从当前位置检查字符串的所有字符t
,而不是字符串的相同字符数。因此,您需要遍历. *s
多少次?的长度t
。
在该迭代中,您需要检查 string 的当前字符s
是否与 string的当前字符进行比较t
。当迭代结束时,如果在该迭代期间访问的所有字符都相同,那么这意味着您找到了匹配项!所以,如果这是真的,那么我们应该增加计数器。
奖励:如果你有时间,并且已经完成了上面讨论的逻辑,想想*s += length;
这个输入:`s = "dabababd", t = "ab"。
推荐阅读
- wireshark - Wireshark 接口
- typescript - OpenTok 事件 Typescript 输入
- r-markdown - 在 Rmarkdown 中控制表格编号
- android - 将数据保存和加载到 Room 数据库是如何工作的?
- android - 远程控制安卓设备
- python - 检查特定列中缺少的行,然后将其添加到数据框中
- angular - 如果我将图像标签添加到组件的 HTML 中,为什么 Angular CLI 会引发解析器错误?
- python - 为什么在 Django 教程“编写第一个 Django 应用程序”的第 4 部分中出现 404 错误
- google-apps-script - Google Apps 脚本 Rhino 与 V8 性能(343 毫秒与 45,042 毫秒)
- powershell - 即使我安装了 polymod,我仍然收到 polymod 错误