【问题标题】:Expression must have class type while using pointers使用指针时,表达式必须具有类类型
【发布时间】:2018-12-12 08:50:50
【问题描述】:

我试图在 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;
}

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

【问题讨论】:

  • s 是一个指向char 的指针,它没有任何substr 方法,你显然把它误认为std::string
  • 你也不能像那样初始化一个数组
  • 子字符串可以相互重叠吗? "aba""abababd"
  • auto d = std::string_view(s, length).substr(0, 2);?
  • 我是 C++ 新手。那我应该怎么初始化呢?

标签: c++ string pointers


【解决方案1】:

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。多少次? 对于t的长度一样多。

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


奖励:如果你有时间,并且已经完成了上面讨论的逻辑,想想*s += length; 和这个输入:`s = "dabababd", t = "ab"。

【讨论】:

  • 我尝试添加该函数并通过以下方式调用它:int length2 = strlen(s); char newT[] = subs(s, 0, length2);它又出错了。
  • OK @Mor,尝试自己调试。如果您仍有问题,请创建MCVE,然后发布一个新问题。我相信我回答了你的问题,所以如果你愿意,可以接受我的回答。我真的可以给你代码并解释给你,但我很确定你自己尝试一下会有更多的收获。所以,尝试一下,努力工作,如果你仍然有麻烦,发布一个新问题。祝你好运!
  • 好的,谢谢,但是您认为我的思路方向正确吗?
  • @Mor 这就是精神!我更新了我的答案,我认为它有帮助......如果它回答了您的问题,请不要忘记接受答案。 :)
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多