首页 > 解决方案 > 表达式在使用指针时必须具有类类型

问题描述

我试图在 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); 有人可以帮忙吗?

标签: c++stringpointers

解决方案


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"。


推荐阅读