如何查找和替换字符串中的所有字符与特定符号C ++ [英] How to find and replace all characters in a string with specific symbols C++

查看:514
本文介绍了如何查找和替换字符串中的所有字符与特定符号C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的初学者,所以如果我以错误的方式接近问题,就很容易。我做这个作为一个任务。我的目的是从用户取一个字符串,并用其他符号替换所有的字符。下面的代码应该找到所有的As,然后用* s替换。我的代码显示完全意外的结果。还有什么是_deciphered.length()的目的。

I am a beginner in programming so take it easy if i approached the problem in a wrong way. i am doing this as an assignment. My purpose is to take a string from user and replace all the characters with another symbol. The code below is supposed to find all the As and replace then with *s. My code is showing totally unexpected result. Also what is the purpose of _deciphered.length().

例如:
I am A bAd boy应该变成I * m * b * d boy

for example: "I Am A bAd boy" should turn into "I *m * b*d boy"

那么我应该为所有大写字母和小写字母和数字实现它,并用不同的符号替换,反之亦然,做一个小的Encode-Decode程序

then i am supposed to implement it for all capital and small letters and numbers and replace with different symbols and vice versa to make a small Encode-Decode program

#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',如果是,请将其设置为'*'

If you need to do this by hand, then bear in mind that an std::string looks like a container of char, so you can iterate over its contents, check if each element is 'A', and if so, set it to '*'.

工作示例:

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

F**Barr*

这篇关于如何查找和替换字符串中的所有字符与特定符号C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆