如何替换字符串中的某个字符?最好是递归方法
How to replace a certain character in a string? Preferably a recursive method
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";
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- 数组元素打印的递归方法
- 我对 leetcode 72 上的递归方法感到茫然
- 使用递归方法遇到分段错误
- 我的链接列表反向递归方法的代码的问题是什么?
- 在链接列表中找到值的递归方法
- 我应该如何实现递归方法以找到在C++中形成最大堆的多种方法
- 使用递归方法将矢量作为输入时进行分割故障
- 使用递归方法的类,使用int矢量元素作为输入
- 3D 迷宫递归方法 - C++
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 迭代器回到递归方法的开头
- 如何创建一个递归方法来比较两个值
- 为什么将十进制转换为二进制的递归方法比迭代、使用和返回字符串更快
- 递归方法中的 C++ 凸包
- 如何将查找组合的几个循环代码转换为递归方法
- 删除单向链表最后一个元素的递归方法
- 反转字符串的递归方法
- 使用递归方法反转ifstream输入
- 如何替换字符串中的某个字符?最好是递归方法