使用指针时表达式必须具有类类型

时间:2018-12-12 08:50:51

标签: c++ string pointers

我正在尝试在string1中计算string2存在多少次。例如: string1 = abababd。 string2 = 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;
}

我一直收到以下问题: 表达式必须具有此行的类类型:char d [] = * s.substr(0,2); 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:6)

substr是类std::string的方法。

您在此处使用C指针(char* s),因此没有substr()可以调用,因此会出错。


当然,我会把实现留给您,但是您可以从create my own 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 迭代。多少次? For t的长度一样。

在该迭代中,您需要检查字符串s的当前字符与字符串t的当前字符比较等于。当迭代结束时,如果该迭代期间访问的所有字符都相同,则意味着您找到了匹配项!因此,如果是正确的,那么我们应该增加计数器。


奖金:如果您有时间并且已经完成了上面讨论的逻辑,请考虑*s += length;和以下输入:`s =“ dabababd”,t =“ ab”。 < / p>