如何替换字符串中的某个字符?优选地是递归方法

时间:2015-11-10 01:03:06

标签: c++ string

我的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(...)

BONUS POINT:是否有任何递归方式来执行相同的工作(替换字符串中的某个字符)?

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

1 个答案:

答案 0 :(得分:1)

  

但是G ++告诉我在dylan :: Replace()中没有匹配函数用于&gt;调用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";