替換字符串中連續出現的指定字符串

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void clearstr(string& str, int end, int len)
{
    while(len--)
        str[end--] = 0;
}
string replacestr(string& str, string& from, string& to)
{
    if(from.size() == 0 || to.size() == 0)
        return str;
    int match = 0;
    for(int i = 0; i < str.size(); ++i)
    {
        if(str[i] == from[match++])
        {
             if(match == from.size())
            {
                clearstr(str, i, from.size());
                match = 0;
            }
        }
        else
        {
            if(str[i] == from[0])
                --i;
            match = 0;
        }
    }
    string cur = "";
    string res = "";
    for(int i = 0; i < str.size(); ++i)
    {
        if(str[i] != 0)
            cur = cur + str[i];
        if(str[i] == 0 && (i == 0 || str[i - 1] != 0))
            {
                res = res + cur + to;
                cur = "";
            }
    }
    res += cur;
    return res;
}
int main()
{
    string str = "123abcabc";
    string from = "abc";
    string to = "x";
    cout << replacestr(str, from, to) << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章