删除字符串中所有给定的子串

来源:互联网 发布:喀秋莎录屏软件 编辑:程序博客网 时间:2024/05/14 06:39

问题描述:在给定字符串中查找所有特定子串并删除,如果没有找到相应子串,则不作任何操作。

要求实现函数:

int delete_sub_str(const char *str, const char *sub_str, char *result_str)

 

【输入】 str:输入的被操作字符串

 

         sub_str:需要查找并删除的特定子字符串

 

【输出】 result_str:在str字符串中删除所有sub_str子字符串后的结果

 

【返回】 删除的子字符串的个数

 

注:

 

I、   子串匹配只考虑最左匹配情况,即只需要从左到右进行字串匹配的情况。比如:

 

在字符串"abababab"中,采用最左匹配子串"aba",可以匹配2个"aba"字串。如果

 

匹配出从左到右位置2开始的"aba",则不是最左匹配,且只能匹配出1个"aba"字串。

 

II、  输入字符串不会超过100 Bytes,请不用考虑超长字符串的情况。

示例输入:str = "abcde123abcd123"

sub_str = "123"

输出:result_str = "abcdeabcd"

返回:2

输入:str = "abcde123abcd123"

sub_str = "1234"

输出:result_str = "abcde123abcd123"

返回:0

 

实现代码如下:

#include <stdio.h>   #include <string.h>   int delete_sub_str(const char *str, const char *sub_str, char *result_str)  {      int count = 0;    int k = 0;    char *p3 = result_str;      for(int i = 0; str[i] != '\0'; i++)      {   int tem = i; //tem保留主串中的起始判断下标位置            int j = 0;          while((str[i] != '\0') && (sub_str[j] != '\0') && (str[i] == sub_str[j]))             {  i++;    j++;  }             if(sub_str[j] != '\0')               {   i = tem;  p3[k] = str[i];   k++;  }             else               {   count += 1;    i--;  }       }      return count;  }    int main()  {      char *str = "12fuck345fuck678fuck9";      char *sub = "fuck";      char res[50] ="";      int count = delete_sub_str(str, sub, res);      printf("子字符串的个数是:%d\n", count);      printf("删除子字符串后:\n%s\n", res);      return 0;  }
本文转自:IT部落