如何替换字符串中的某个字符?最好是递归方法

How to replace a certain character in a string? Preferably a recursive method

本文关键字:字符 递归方法 何替换 替换 字符串      更新时间:2023-10-16

My dylan::Replace()函数应该以字符串为参数,用星号('*')替换空格并返回字符串。下面的代码就是我所拥有的:

#define n 0
namespace dylan{
    string Replace(string);
    string Replace (string s){
        if (s.substr(n)=="")
            cout << "string is empty n";
        else
            s.replace(s.begin(),s.end(),' ','*');
        return s;
    }
}
using namespace dylan;
int main (int argc, char * argv[]){
    string s="a b c";
    string sAfter=Replace(s);
    // some more stuff
}

但是G++告诉我,在dylan::Replace()中有no matching function for call to std::basic_string<CharT,_Traits,_Alloc>replace(...)

优点:有任何递归方法可以完成相同的工作(替换字符串中的某个字符)吗?


问题更新:我修改并运行了程序,但它没有完成我想要的工作。相反,它多次打印星号。

但是G++告诉我,在dylan::Replace()中,对std::basic_stringreplace(…)的>调用没有匹配的函数

std::string::replace获取字符串中的位置范围和新内容作为输入。它不能用另一个字符替换一个字符,可能的解决方案是std::replace_copy:

#include <string>
#include <iostream>
#include <algorithm>
namespace dylan{
    std::string Replace(const std::string &s){
        std::string res(s.size(), ' ');
        std::replace_copy(s.begin(), s.end(), res.begin(),
                  ' ', '*');
        return res;
    }
}
int main()
{
    std::string s="a b c";
    std::string sAfter = dylan::Replace(s);
    std::cout << sAfter << "n";
}

递归变体:

std::string ReplaceReq(std::string::const_iterator it, std::string::const_iterator end)
    {
        std::string res;
        if (it == end)
            return res;
        res += *it == ' ' ? '*' : *it;
        return res + ReplaceReq(it + 1, end);
    }

用法:

std::string sAfter2 = dylan::ReplaceReq(s.begin(), s.end());
std::cout << sAfter2 << "n";