繁体   English   中英

从主字符串中查找子字符串

[英]finding substring from a main string

我的任务是从主字符串中找到一个子字符串,并将指针返回到主字符串中该子字符串的第一个字符,并且需要在"?"之后停止搜索 并且代码必须在没有string.h情况下完成。 我给我的代码运行正常,但自动检查器表示相反,检查器表示

test_source.c:195:F:test_es_strstr:test_es_strstr:0: [07_altstring.d] Wrong return value with string "Foobarbaz?asd:w" and substring "baz?": Got 0x72, expected 0x7ffeb8b8a306

所以检查器说我的指针不在正确的位置..但是对我来说,需要帮助。

我的代码=

const char *es_strstr(const char *str1, const char *str2) {
    int i = 0;
    int j = 0;

    while (str1[j] != '?')    ///function has to stop the search to 
                             /// a question mark
    {
        if (*str1 == str2[i])    ///comparing main string first character
                                /// to substring first character
        {
            i++;
            ++str1;
            if (*str1 == str2[i])   ///if first ones are match then look
                                    /// for the next character matching
            {
                i++;
                ++str1;
                if (*str1 == str2[i])  /// finally if 2nd is match then 3rd
                {
                    --str1;
                    --str1;
                    printf("%c\n", *str1);
                    return *str1;
                }

            }
        }
        j++;
        i = 0;
        ++str1;
    }
    return NULL;           ///if nothing matches need to return NULL

int main(void) {
    char *main = "Foobarbaz?asd:w";
    char *sub = "baz?";
    es_strstr(main, sub);
    }

我认为你应该返回指针,即

return str1;

代替

return *str1;

* str表示str1指向的字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM