C++:递归地将字符串中一个字母的所有实例替换为另一个字母
C++: recursively replace all instances of a letter in a string with another letter
我只是在浏览一些教科书上的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!
考虑到"用另一个字母替换字符串中一个字母的所有实例"意味着必须更改源字符串。这反过来意味着源字符串必须通过引用传递给函数。
相关文章:
- 如何将模板的实例传递给另一个模板的另一个实例?
- 如何在另一个类中创建类的实例?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 重载运算符*以获取对另一个类的实例的引用
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 如何正确实例化静态字段 tat 是另一个类对象
- C++ - 使用另一个类的构造函数实例化一个对象
- 如何使用另一个模板化类的实例模板化类?
- 在另一个类中创建类实例时出现问题
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 另一个类中嵌套模板的外部实例化
- 如何为包含另一个类实例的数组制作常量 getter?
- 如何将模板化类实例作为模板参数传递给另一个模板?
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 如何将对象函数的实例传递给另一个函数
- "new operator"将另一个类实例化为工厂?
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 类实例的C++/向量作为另一个类的属性