Mor*_*Mor 3 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;
}
Run Code Online (Sandbox Code Playgroud)
我一直收到这个问题:Expression必须有这一行的类类型: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;
}
Run Code Online (Sandbox Code Playgroud)
所以现在,您应该关注如何检查字符串中当前子字符串是否匹配.所以,你需要改变这个:
if (*s == *t)
counter++;
Run Code Online (Sandbox Code Playgroud)
t从当前位置检查字符串的所有字符与字符串的相同字符数.所以,你需要迭代通过*s.多少次?为了尽可能的长度t.
在该次迭代,你需要检查该字符串的当前字符s是比较平等的字符串的当前字符t.当迭代结束时,如果在该迭代期间访问过的所有字符都相同,则表示您找到了匹配项!所以,如果这是真的,那么我们应该增加计数器.
额外奖励:如果你有时间,并完成了上面讨论的逻辑,*s += length;那就考虑一下这个输入:`s ="dabababd",t ="ab".
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |