Implement strstr
Implement strstr
我正在尝试从头开始编写strstr函数。我在调试器中逐行检查了我的代码,它运行得很好。但是,它没有正确保存搜索的子字符串的开头。因此,它没有适当地归还它。我没有太多编程经验,所以我的代码有点混乱和复杂。然而,它在大多数情况下确实有效。下面是我的代码(为我的教授和大家评论,看看我做了什么)。(此外,我的教授已经表示接受后藤函数)
char *strgstr(const char *str1, const char *str2)
{
//I went through this function line by line with the debugger
//The only problem with it is when I go to save the location of the
//substring in str1.
//I posted a question on stackoverflow and I was able to get it to compile
//but it still doesn't save and return properly. The rest of the function works.
int len_str1=strlen(str1);
int len_str2=strlen(str2);
char *save_str=NULL;
int i=0;
for(; i<len_str1; i++)
{
there:
if(str1[i]==str2[0]) //checks if this is the beginning of str2
{
save_str=(char*)str1[i]; //This is where the problem is.
int j=0; //start at beginning of str2
for(;i<len_str1;i++) //index str1
{
if(j<len_str2) //checks if we've finished searching str2
{
if(str1[i]!=str2[j])
{
goto there;
}
j++;
}
else
{
return save_str; //does not return properly. I can't figure out how to save a particular point in the index to a pointer.
}
}
}
}
}
您编写为的行
save_str=(char*)str1[i]; //This is where the problem is.
应该是(例如)
save_str = str1 + i;
您的原始版本将字符的数值视为指针,这是完全错误的。
为什么需要如此复杂的代码?
const char *strgcstr(const char *haystack, const char *needle)
{
while(*haystack!=0)
{
if( (*haystack == *needle) &&
(strncmp(haystack, needle, strlen(needle)) == 0) )
return haystack;
haystack++;
}
return NULL;
}
class Solution {
public int strStr(String haystack, String needle) {
String res ="";
int pos = 0;
if(needle.length() == 0){
return 0;
}
if(haystack.equals(needle)){
return 0;
}
if (needle.length()>haystack.length()||haystack.length() == 0){
return -1;
}
for(int i =0; i<haystack.length();i++){
if(haystack.charAt(i) == needle.charAt(0)){
if(i+needle.length() <= haystack.length()){
res = haystack.substring(i,i+(needle.length()));
if (res.equals(needle)){
pos = i;
return pos;
}
}
else{
return -1;
}
}
else{
continue;
}
}
return -1;
}
}
相关文章:
- 有 strstr() 的 constexpr 版本吗?
- Leetcode 28 - Implement strStr(): question
- strstr 函数误打误打
- "Has a" C++关系,最佳做法是让一个类"implement"多个抽象基类?
- char*newx=p+strlen(str1);这将如何执行,因为strstr将返回指向另一个字符串的第一个匹配字符的
- SIMD: implement _mm256_max_epu64_ and _mm256_min_epu64_
- To implement FlannBasedMatcher
- C++String.h字符表截断不带strstr的单词
- Eclipse "implement method"函数不适用于模板类
- 如何比较strstr(lpcwstr,char*);
- strstr 返回如何不是一个常数
- 在C MBED中使用strstr,打印结果
- 性能比较:strstr()与std::string::find()
- 如何修复对strstr没有匹配函数调用的问题
- G++ strstr 说从常量字符 * 到字符 * 的转换无效
- 使用 strstr 的计数不正确
- 性能标准::strstr vs. 标准::字符串::查找
- strstr函数与2015年相比不起作用
- void_t "can implement concepts" ?
- Implement strstr