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

标签 c++ replace

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

相关文章:

c++ - 如果你在 vector 拷贝中放一个常量会怎样?或移动?

c++ - friend 类可以在 C++ 中调用私有(private)构造函数吗? (什么是单例)

ASP.NET MVC Controller参数处理

mysql - 在 mysql 中指定 id 替换为

c++ - 如何从双指针数组创建 Eigen::VectorXd

c++ - 使用istringstream处理一个变长的内存块

.net - 托管 C++ 中的 ServiceController? (。网)

search - 如何在 Notepad++ 中搜索、替换和保留大小写?

JavaScript 正则表达式 : search and replace tags in string

powershell - 替换文件中的字符串,并获得有关所做操作的一些反馈