如何使用特定符号 C++ 查找和替换字符串中的所有字符

Posted

技术标签:

【中文标题】如何使用特定符号 C++ 查找和替换字符串中的所有字符【英文标题】:How to find and replace all characters in a string with specific symbols C++ 【发布时间】:2013-10-23 15:46:10 【问题描述】:

我是编程初学者,所以如果我以错误的方式解决问题,请放轻松。我这样做是作为一项任务。我的目的是从用户那里获取一个字符串并用另一个符号替换所有字符。下面的代码应该找到所有的 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;

【问题讨论】:

【参考方案1】:

由于您似乎已经在使用标准库,

#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**巴尔*

【讨论】:

这仅在找到第一个 a 并仅返回该单词之前有效。例如,如果我输入“bad bay”,它会返回“bd”。我如何让它返回完整的字符串“bd b*y”? @UsamaKhurshid 不,你错了。它将所有A 字符替换为* @UsamaKhurshid 我试过了。要么你在尝试别的东西,要么你的标准库实现被破坏了。 您发布的解决方案现在有效!谢谢..我想知道你发布的第一个有什么问题!【参考方案2】:

您可以使用std::replace

std::replace(deciphered.begin(), deciphered.end(), 'A', '*');

此外,如果您想替换多个符合特定条件的值,您可以使用std::replace_if

std::replace_if(deciphered.begin(), deciphered.end(), myPredicate, '*');

如果字符匹配要替换的条件,myPredicate 返回true。例如,如果你想同时替换 aAmyPredicate 应该为 aA 返回 true,而对于其他字符则返回 false。

【讨论】:

【参考方案3】:

我个人会使用正则表达式替换用 * 替换“A 或 a”

看看这个答案以获得一些指导:Conditionally replace regex matches in string

【讨论】:

虽然可以使用正则表达式,但std::replace 更简单,开销也更少。

以上是关于如何使用特定符号 C++ 查找和替换字符串中的所有字符的主要内容,如果未能解决你的问题,请参考以下文章

如何查询我的所有视图设计以查找 SQL Server 中的特定字符串?

Perl:在多个文本文件中查找和替换特定字符串

SQL如何查找和删除MYSQL数据库中包含特定字符串的记录

如何用python查找和替换json文件中的特定字符串

替换 C++ 字符串中的标点符号

如何在目录树中递归查找和替换所有出现的字符串? [复制]