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

C++ 使用指针时,表达式必须具有类类型,c++,string,pointers,C++,String,Pointers,我试图在string1中计算string2存在的次数。例如: string1=ababad。 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

我试图在string1中计算string2存在的次数。例如: string1=ababad。 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); 有人能帮忙吗?

是一种上课的方法

这里使用的是C指针(
char*s
),因此没有要调用的
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
的长度相同

在该迭代中,您需要检查字符串
s
的当前字符是否与字符串
t
的当前字符相等。当迭代结束时,如果在该迭代期间访问的所有字符都相同,则表示您找到了匹配项!如果这是真的,那么我们应该增加计数器



奖励:如果你有时间,并且已经完成了上面讨论的逻辑,考虑
*s+=length
s
是一个指向
char
的指针,它没有任何
substr
方法,你显然把它和
std::string
错了,而且你不能初始化这样的数组,子字符串会相互重叠吗<代码>在
“abababad”
中的“aba”
自动d=std::string\u视图(s,长度).substr(0,2)?我是C++新手。那么我应该如何初始化它呢?我尝试添加函数并通过以下方式调用它:int length2=strlen(s);char newT[]=subs(s,0,长度2);它再次出错。好的@Mor,试着自己调试它。如果你仍然有困难,创建一个新的问题,然后发布一个新的问题。我相信我回答了你的问题,所以如果你愿意,你可以接受我的回答。我真的可以给你的代码,并解释给你,但我敢肯定,你会有更多的收益,通过尝试自己。所以,尝试一下,努力学习,如果你仍然有困难,就发布一个新问题。祝你好运好的,谢谢,但是你认为我的思维方式是正确的吗?@Mor这就是精神!我更新了我的答案,我认为它有帮助。。。如果答案回答了你的问题,别忘了接受答案。:)