C++:递归地将字符串中一个字母的所有实例替换为另一个字母

C++: recursively replace all instances of a letter in a string with another letter

本文关键字:实例 另一个 替换 一个 递归 字符串 C++      更新时间:2023-10-16

我只是在浏览一些教科书上的c ++问题,其中之一是编写一个函数,该函数递地将字符串中某个字母的所有实例替换为另一个字母。我知道有预先存在的函数,但是由于本章侧重于递归,因此这个问题坚持解决方案必须是递归的。所以我用 c++ 写了所有这些,这很好,但后来我读了这个问题的脚注,它说的是:"对于字符串对象的操作,只允许使用长度和长度(即大小(的方法以及运算符+"。咦?我只是不明白如果没有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);
}

这是一个演示。

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

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

考虑到脚注

我读了这个问题的脚注,它说的是:"对于 字符串对象的操作,只有方法和长度(即 大小(以及运算符 +" 是允许的。

似乎该函数应该如下所示

std::string & replace( std::string &in, char from, char to, std::string::size_type pos = 0 )
{
if ( pos < in.size() )
{
if ( in.at( pos ) == from )
{
in.at( pos ) = to;
}
replace( in, from, to, pos + 1 );
}
return in;
}   

这是一个演示程序

#include <iostream>
#include <string>
std::string & replace( std::string &in, char from, char to, std::string::size_type pos = 0 )
{
if ( pos != in.size() )
{
if ( in.at( pos ) == from )
{
in.at( pos ) = to;
}
replace( in, from, to, pos + 1 );
}
return in;
}   
int main() 
{
std::string in( "Hell& W&rld!" );
char from = '&';
char to = 'o';
std::cout << in << " --> "; 
std::cout << replace( in, from, to ) << 'n';
return 0;
}

它的输出是

Hell& W&rld! --> Hello World!

考虑到"用另一个字母替换字符串中一个字母的所有实例"意味着必须更改源字符串。这反过来意味着源字符串必须通过引用传递给函数。