[英]How to find and replace all characters in a string with specific symbols C++
我是编程的初学者,所以如果我以错误的方式解决问题,请放轻松。 我这样做是作为一项任务。 我的目的是从用户那里获取一个字符串,并将所有字符替换为另一个符号。 下面的代码应该找到所有的As,然后替换为* s。 我的代码显示出完全意外的结果。 _deciphered.length()的用途也是什么。
例如:“我是bAd男孩”应该变成“我* m * b * d男孩”
然后我应该对所有大写字母,小写字母和数字实施该编码,并用不同的符号替换,反之亦然,以制作一个小的编码解码程序
#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
和A
返回true
,为其他字符返回false。
我个人会使用常规的expssion替换来用*替换“ A或a”
看一下一些指针的答案: 有条件地替换字符串中的正则表达式匹配项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.