如何查找字符串中的所有字符并将其替换为特定符号C++
How to find and replace all characters in a string with specific symbols C++
我是编程初学者,所以如果我以错误的方式处理问题,请放轻松。 我这样做是作为一项任务。我的目的是从用户那里获取一个字符串,并用另一个符号替换所有字符。下面的代码应该找到所有 As 并替换为 *s。我的代码显示完全出乎意料的结果。还有_deciphered.length()的目的是什么。
例如:"我是bad男孩"应该变成"I * m * b*d boy"
然后我应该为所有大写字母、小写字母和数字实现它,并用不同的符号替换,反之亦然,以制作一个小型的编码解码程序
#include <iostream>
#include <string>
using namespace std;
string cipher (string);
void main ()
{
string ciphered, deciphered;
ciphered="String Empty";
deciphered="String Empty";
cout<<"Enter a string to "Encode" it : ";
cin>>deciphered;
ciphered=cipher (deciphered);
cout<<endl<<endl;
cout<<deciphered;
}
string cipher (string _deciphered)
{
string _ciphered=(_deciphered.replace(_deciphered.find("A"), _deciphered.length(), "*"));
return _ciphered;
}
由于您似乎已经在使用标准库,
#include <algorithm> // for std::replace
std::replace(_deciphered.begin(), _deciphered.end(), 'A', '*');
如果您需要手动执行此操作,请记住 std::string
看起来像一个容器 char
,因此您可以迭代其内容,检查每个元素是否'A'
,如果是,请将其设置为 '*'
。
工作示例:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s = "FooBarro";
std::cout << s << std::endl;
std::replace(s.begin(), s.end(), 'o', '*');
std::cout << s << std::endl;
}
输出:
福巴罗
F**巴尔*
您可以使用
std::replace
std::replace(deciphered.begin(), deciphered.end(), 'A', '*');
此外,如果要替换与特定条件匹配的多个值,可以使用std::replace_if
。
std::replace_if(deciphered.begin(), deciphered.end(), myPredicate, '*');
其中myPredicate
返回true
字符是否与要替换的条件匹配。例如,如果要同时替换 a
和 A
,myPredicate
应该为 a
返回 true
,A
返回其他字符的 false 和 false。
我个人会使用常规的 experssion 替换来将"A 或 a"重新调整为 *
看看这个答案的一些指针:有条件地替换字符串中的正则表达式匹配
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 如何用转义符替换字符串中的所有特殊字符
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 在一个读写器队列中,我可以用volatile替换原子吗
- 用符号版本替换对函数的所有调用
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 替换基于地图的所有引用
- 按平均值替换数组中的元素
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 初始化 std::vector 替换为单大括号而不是双大括号
- 删除/替换C++字符串中的多字符 (ÿû)
- 将 malloc 替换为数组
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 如何在C++中用'\'替换''来处理转义序列?
- 替换密码:哪一个?
- 替换 C++17 中移除的绑定 1st
- 将 Boost MPL 容器替换为 C++17 功能
- C++:如何用单个命令替换复杂的迭代?
- C++ 替换字节数组中项的顺序