c – 表达式在使用指针时必须具有类类型
我试图在string1中计算string2存在多少次.例如:
string1 = abababd. string2 = ab. 结果:3. (我必须使用指针来解决这个问题) 到目前为止我所拥有的: int mystr(char* s,char* t) { int counter = 0; int length = strlen(t); while (*s != ' ') { char d[] = *s.substr(0,2); if (*s == *t) counter++; *s += length; } return counter; } 我一直收到这个问题: 解决方法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 != ' ') { // 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”. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |