c++ 之 删除字符串中的子串 两种方式

时间:2019-01-11
本文章向大家介绍c++ 之 删除字符串中的子串 两种方式,主要包括c++ 之 删除字符串中的子串 两种方式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C++实现删除给定字符串的给定字符串思路主要有这么几种实现方式:

1.KMP算法
2.用STL的string的 find,然后用erase
3.用C的strstr找到字串位置,然后用strncpy写到新串中
4.用boost库,用正则表达式

测试代码:

#include <QCoreApplication>
#include<iostream>
#include <string>
using namespace std;

void deletesub(string &str,const string &sub,int n)
{
    int m,flag=0,num=0;           //num是子串出现的次数
   while(flag==0)
   {
        m=str.find(sub);
        if(m<0)
            flag=1;
        else
        {
          str.erase(m,n);           //删除子串
          num++;
        }
   }
//  cout<<num<<endl;          //子串出现的次数
    cout<<str<<endl;         // 输出删除后的字符串
}

void deletestr(const char *str, const char* sub_str, char *result)
{
    int sublen = 0;         //获得子串的长度
    const char *t = sub_str;
    while(*t++ != '\0')
    {
        sublen++;
    }

    int pos = 0;
    int pp = 0;
    int repos = 0; // 结果子串的索引
    while(*(str + pos) != '\0')
    {
        char t = *(str + pos);
        if(t == *(sub_str + pp)) // 重复子串起始位置
        {
            *(result + repos) = t;
            repos++;

            if(pp < sublen - 1) // 还未完全重复
            {
                pp++;
            }
            else if(pp == sublen - 1) // 完全重复了
            {
                pp = 0;
                repos -= sublen; // 回溯下标位置
            }
        }
        else{ // 不是一样的字符
            *(result + repos) = t;
            repos++;
        }
        pos++;
    }
    *(result + repos) = '\0';
    cout<<result<<endl;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

// 第一种方法
//    char str[100],sub[100];
//    cin>>str;
//    cin>>sub;
//    char result;
//    deletestr(str,sub,&result);

//第二种方法
    string str,sub;
    cin>>str;
    cin>>sub;
    int n=sub.size();
    deletesub(str,sub,n);

    return a.exec();
}

参考链接:

http://www.cnblogs.com/calamus/p/5862230.html

https://blog.csdn.net/yishizuofei/article/details/79059804