《C和指针》章节后编程练习解答参考——6.2

《C和指针》——6.2

题目:

  编写一个函数,删除源字符串中含有的子字符串部分。

函数原型:

  int del_substr(char *str, char const *substr);

解答代码:

#include <stdio.h>

int del_substr(char *str, char const *substr)
{
    if ((*str != NULL) && (*substr != NULL))
    {
        for(; *str != ''; str++)
        {
            if (*str == *substr)
            {
                int i=0;
                while ((*(str+i) != '') && (*(substr+i) != ''))
                {
                    if (*(str+i) == *(substr+i))
                    {
                        i++;    //保持两个字符串指针同时加1
                    }
                    else
                        break;
                }

                if ((*(substr+i) == ''))    //子字符串检测结束
                {
                    for(; *(str+i) != ''; str++)
                    {
                        *str = *(str+i);
                    }
                    *str = '';    //将源字符串后边的字符舍弃
                    return 1;
                }
                else
                {
                    return 0;                
                }
            }
        }
    }
    return 0;
}

int main()
{
    char source[] = "ABCDEFGHIJKLMN";
    char subsource[] = "DEF";

    printf("%s
", source);
    printf("%s
", subsource);

    if (del_substr(source, subsource) == 1)
    {
        printf("Delete the substr:
");
        printf("%s", source);
    }
    else
        printf("Have not found the substr!");

    getchar();
    return 0;
}

注:

1、应先判断源字符串中是否包含子字符串,检测时要保持两个指针增量同步。

2、子字符串对比完后判断是否包含于源字符串。

原文地址:https://www.cnblogs.com/microxiami/p/4966844.html