我是编程初学者,所以如果我以错误的方式处理问题,请放轻松。我这样做是作为一项任务。我的目的是从用户那里获取一个字符串并将所有字符替换为另一个符号。下面的代码应该找到所有的 As 然后用 *s 替换。我的代码显示出完全出乎意料的结果。还有 _deciphered.length() 的目的是什么。
例如: “I Am A bad boy”应该变成“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;
}
输出:
FooBarro
F**Barr*
关于c++ - 如何用特定符号查找和替换字符串中的所有字符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19546367/