删除字符串中指定的字符串 并返回在原字符串中出现的指定字符串的次数

#include <iostream>
#include <string.h>
using namespace std;

#define Maxsize 100

void cover(char ch[], char substr[], int index)
{
    int size = strlen(ch);
    int sub_size = strlen(substr);
    int result = 0, j = 0;
   
    if((index+sub_size)>=size)
       ch[index] = '\0';
    else
    {
        for(int i=index+sub_size;i<size;i++)
        {
                 ch[index++] = ch[i];
        }
    }
    ch[size-sub_size] = '\0';
}

int findstring(char ch[], char substr[])
{
    int size = strlen(ch);
    int sub_size = strlen(substr);
    int result = 0, j = 0, a[10];;
   
    for(int i=0;i<size;i++)
    {
         if(substr[j] == ch[i])
            {
                 if(j == (sub_size-1))
                 {
                      a[result++] = i-sub_size+1;
                      j=0;
                 }           
                 else
                 {
                     j++;
                 } 
            }
            else
            {
                j = 0;
            }
    }
    for(int i=0;i<result;i++)
    {
            cover(ch, substr, a[i]-i*sub_size);
    }
    return result;
}

int main(void)
{
    char ch[Maxsize] ,sub_str[Maxsize];
    int cnt;
   
    cout<<"Please input the string:";
    gets(ch);
    cout<<"Please input the substring your want to delete:";
    gets(sub_str);
    cnt = findstring(ch,sub_str);
    cout<<"The result is ";
    cout<<ch<<endl<<"The sum of the string appear is "<<cnt<<endl;
    return 0;
}                                                                                                                                                                                                                                       

posted @ 2012-09-23 12:33  SA高处不胜寒  阅读(493)  评论(0编辑  收藏  举报