如何查找字符串中的所有字符并将其替换为特定符号C++

How to find and replace all characters in a string with specific symbols C++

本文关键字:替换 C++ 符号 字符 查找 何查找 字符串      更新时间:2023-10-16

我是编程初学者,所以如果我以错误的方式处理问题,请放轻松。 我这样做是作为一项任务。我的目的是从用户那里获取一个字符串,并用另一个符号替换所有字符。下面的代码应该找到所有 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字符是否与要替换的条件匹配。例如,如果要同时替换 aAmyPredicate 应该为 a 返回 trueA 返回其他字符的 false 和 false。

我个人会使用常规的 experssion 替换来将"A 或 a"重新调整为 *

看看这个答案的一些指针:有条件地替换字符串中的正则表达式匹配