c++ - C++:用另一个字母递归地替换一个字母中所有字母的实例

标签 c++ string recursion replace function-definition

我只是在讲一些教科书中的c++问题,其中之一是编写一个函数,该函数将一个字符串中某个字母的所有实例用另一个字母递归替换。我知道有一些预先存在的函数,但是因为本章着重于递归,所以这个问题坚持认为解决方案必须是递归的。因此,我用c++编写了所有内容,这很好,但是随后我阅读了该问题的脚注,它的含义是:“对于字符串对象的操作,只允许使用at和length(即size)的方法,以及运算符+”。哇?我只是看不到没有str.substr(pos,len)怎么能做到这一点,但是如果有人能找到办法,我会很高兴。多亏了那个特别的人哟。

这是仓鼠大脑可以想到的最好的代码(也是在开始时注释了一个小的迭代替代方法)。

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

// iterative solution
/* string replace (string in, char from, char to) {
  string res;
  for (int i{0}; i < in.length(); i++) {
    if (in.at(i) == from)
      res += to;
    else
      res += in.at(i);
    }
  return res;
} */

// recursive solution
string replace (string in, char from, char to) {
  if (in.empty())
    return "";
  char first{in.at(0)};
  if (first == from)
    return to + replace (in.substr(1), from, to);
  else
    return in.at(0) + replace (in.substr(1), from, to);
}

int main () {
  string in;
  char from, to;
  cout << "Word: ";
  cin >> in;
  cout << "from: ";
  cin >> from;
  cout << "to: ";
  cin >> to;
  cout << in << " --> " << replace (in, from, to) << '\n';
  return 0;
}

最佳答案

只需提供一个跟踪索引的默认参数即可:

string replace(string in, char from, char to, int i = 0) 
{
  if (i == in.length()) 
    return in;
  if (in.at(i) == from) 
    in.at(i) = to;
  return replace(in, from, to, i + 1);
}

这是demo

这仅使用at()length(),甚至不使用+

另外,请避免使用using namespace std;,这是不好的做法。

关于c++ - C++:用另一个字母递归地替换一个字母中所有字母的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61740583/

相关文章:

c++ - 内存有效的字符串 vector

c++ - std::string 及其自动调整内存大小

java - 使用java设置字符串颜色

ios - 网络完成 block 、递归和 ARC 保留循环

c++ - 添加 const 正确性

c++ - 函数定义中的未命名参数

c++ - string::size_type 真的大到可以容纳任何字符串吗?

c++ - 如何在 std::list 中使用递归?

c - 如何递归地遍历文件夹并计算总文件大小

c++ - 使用 fstream 对象将文件中的信息存储到变量中