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

advertisements

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


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*