用于查找子字符串的C ++代码,逻辑错误

时间:2015-05-24 08:55:11

标签: c++

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

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) == '\0') //checks if the main string is not null.
        return s1;



    while (*(s1 + i) != '\0' && *(s2 + i) != '\0')// 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) == '\0')
                return NULL;

            t = i;//stores the position where the first substrign was found
            while (s1[i] == s2[j] && s1[i] != '\0' && s2[j] != '\0')
            {
                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) == '\0' && *(s2 + i) != '\0')
    return NULL;

if (*(s1 + i) != '\0' && *(s2 + i) == '\0')
    return s1;

if (*(s1 + i) == '\0')
    return s1;


while (*(s1 + i) != '\0')
{
    while (s1[i] != s2[j] && s1 != NULL)
    {
        i++;
        j = 0;
    }
    if (*(s1 + i) == '\0')return NULL;
    t = i;
    while (s1[i] == s2[j] && s1[i] != '\0'&&s2[j] != '\0')
    {
        i++;
        j++;
    }
    if (l == j){
        s3 = &s1[t];
        return s3;
    }
}
return NULL;

}

无论如何都要使代码更有效率。我正在使用此代码从主字符串中查找子字符串。

1 个答案:

答案 0 :(得分:1)

这行有一个错误:

while (*(s1 + i) != '\0' && *(s2 + i) != '\0')

除非在字符串的相同位置有'\0',否则这不存在。你应该使用||,你也应该考虑索引。也许您想使用j来编制s2

的索引
if (*(s1 + i) == '\0')
                return NULL;

当您到达NULL的末尾时,上面的代码会返回s1。如果s2恰好位于s1的末尾,会发生什么?它将返回NULL。所以这是另一个错误,因为它假设如果你到达字符串的末尾,那么找不到子字符串。

您还应该检查ij的进展情况。如果它没有从while循环退出,那么它永远不会到达return。如果使用“run to cursor”调试到return语句,调试器是否会跳转到那里?如果程序没有永远运行,那么它最终会停止,因此它不会永远运行while。你应该检查所有这些。

我只是给你一些如何解决问题的想法,我不想解决你的功课。