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;
}
You can use
std::replace
Also, you can use
std::replace_if
if you want to replace multiple values that match a certain criteria.where
myPredicate
returnstrue
if the character matches the criteria to be replaced. So for example, if you want to replace botha
andA
,myPredicate
should returntrue
fora
andA
and false for other characters.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
Since you seem to be using the standard library already,
If you need to do this by hand, then bear in mind that an
std::string
looks like a container ofchar
, so you can iterate over its contents, check if each element is'A'
, and if so, set it to'*'
.Working example:
Output: