c++代码查找子字符串,逻辑错误

C++ code for finding a substring, logical error

本文关键字:错误 字符串 代码 查找 c++      更新时间:2023-10-16

嘿,伙计们,我已经做了一个函数,应该从主字符串中找到一个子字符串,但它不工作,这里是代码:

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。所以这是另一个错误,因为它假设如果你到达字符串的末尾,那么子字符串没有找到。

您还应该检查ij的进展情况。如果它没有退出while循环,那么它永远不会到达return。如果你用"运行到光标"来调试你的return语句,调试器在那里跳跃吗?如果程序不是永远运行,那么它最终会停止,所以它不会永远运行while。你应该检查所有这些

我只是给你一些解决问题的想法,我不想解决你的作业