How to find and replace all characters in a string

2019-08-09 18:58发布

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().

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

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;
}

标签: c++ replace
3条回答
ゆ 、 Hurt°
2楼-- · 2019-08-09 19:37

You can use std::replace

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

Also, you can use std::replace_if if you want to replace multiple values that match a certain criteria.

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

where myPredicate returns true if the character matches the criteria to be replaced. So for example, if you want to replace both a and A, myPredicate should return true for a and A and false for other characters.

查看更多
家丑人穷心不美
3楼-- · 2019-08-09 19:49

I would personally use regular experssion replace to repace "A or a" with *

Have a look at this answer for some pointers: Conditionally replace regex matches in string

查看更多
We Are One
4楼-- · 2019-08-09 19:58

Since you seem to be using the standard library already,

#include <algorithm> // for std::replace

std::replace(_deciphered.begin(), _deciphered.end(), '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 '*'.

Working example:

#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;
}

Output:

FooBarro

F**Barr*

查看更多
登录 后发表回答