c++代码查找子字符串,逻辑错误
C++ code for finding a substring, logical error
嘿,伙计们,我已经做了一个函数,应该从主字符串中找到一个子字符串,但它不工作,这里是代码:
char *mystrstr (char *s1, char *s2)
{
int i=0, j=0, k=0,t=0, l;
char* s3 = NULL;
char* s4 = NULL;
l = mystrlen (s2);
k = mystrlen(s1);
//s1 is the main string and s2 is the substring
if (*(s1 + i) == ' ') //checks if the main string is not null.
return s1;
while (*(s1 + i) != ' ' && *(s2 + i) != ' ')// if both the strings are not null then the program proceeds
{
while (s1[i] != s2[0] && s1 != NULL)//loop runs till the first letter of substring is found in the main string.
{
i++;
}
if (*(s1 + i) == ' ')
return NULL;
t = i;//stores the position where the first substrign was found
while (s1[i] == s2[j] && s1[i] != ' ' && s2[j] != ' ')
{
i++;//takes tho the nextl letter of the main string
j++;//to the next letter of the substring.
}
}
if (l == j)//if all letters of the substring is found in the main string only then this condition will be true.
{
s3 = &s1[t];
}
return s3;
}
谁能告诉我出了什么问题,或者至少给我一个提示?所以根据给出的建议,我已经改变了我的代码,它给了我想要的结果。下面是新代码-
char *mystrstr(char *s1, char *s2){
int i = 0, j = 0, k = 0, t = 0, l;
char* s3 = NULL;
char* s4 = NULL;
l = strlen(s2);
k = strlen(s1);
if (*(s1 + i) == ' ' && *(s2 + i) != ' ')
return NULL;
if (*(s1 + i) != ' ' && *(s2 + i) == ' ')
return s1;
if (*(s1 + i) == ' ')
return s1;
while (*(s1 + i) != ' ')
{
while (s1[i] != s2[j] && s1 != NULL)
{
i++;
j = 0;
}
if (*(s1 + i) == ' ')return NULL;
t = i;
while (s1[i] == s2[j] && s1[i] != ' '&&s2[j] != ' ')
{
i++;
j++;
}
if (l == j){
s3 = &s1[t];
return s3;
}
}
return NULL;
}
是否有办法使代码更有效?我使用此代码来查找主字符串的子字符串。
这一行有错误:
while (*(s1 + i) != ' ' && *(s2 + i) != ' ')
这将不存在,除非在字符串的相同位置有一个' '
。你应该使用||
,你也应该考虑索引。也许你想用j
来索引s2
。
if (*(s1 + i) == ' ')
return NULL;
当到达s1
的末尾时,上面的代码返回NULL
。如果s2
正好在s1
的末尾会发生什么?它将返回NULL
。所以这是另一个错误,因为它假设如果你到达字符串的末尾,那么子字符串没有找到。
您还应该检查i
和j
的进展情况。如果它没有退出while
循环,那么它永远不会到达return
。如果你用"运行到光标"来调试你的return
语句,调试器在那里跳跃吗?如果程序不是永远运行,那么它最终会停止,所以它不会永远运行while
。你应该检查所有这些
我只是给你一些解决问题的想法,我不想解决你的作业
相关文章:
- 由cin中的字符串中未捕获空白引起的分割错误
- 将 GetLastError() 转换为带有错误字符串的异常
- Rapidjson 解析错误:字符串 (207) 中的编码无效
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何检索 DirectX 9 的错误字符串
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 错误字符串下标超出c++范围
- 获取Openssl证书错误中的错误字符串
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 语法错误字符串方法C++
- 对于静态错误字符串,哪个的内存/性能效率更高,或者有替代方案
- 使用 strtok() 的错误字符串比较
- C++ 中的运行时错误字符串声明
- 我收到错误:字符串声明上的 C2501
- GCC:为什么一行代码中的错误(字符串和NULL的比较)会导致一长串错误消息
- 错误C2059:语法错误:'字符串'
- 致命错误:字符串:没有这样的文件或目录编译终止
- C++错误:字符串下标超出范围
- 这里面有什么错误?字符串赋值
- 是否有标准的方法来查询EGL错误字符串