Replacing letters in a string by other ones
Sep 3, 2020 at 7:57pm UTC
Im having trouble replacing letters of the alphabet with one and other,
for instance: A->E
B->R and so on..
I've been using the following code:
1 2 3
std::replace( s.begin(), s.end(), 'a' , 'e' );
std::replace( s.begin(), s.end(), 'b' , 'r' );
std::replace( s.begin(), s.end(), 'm' , 'a' );
However from my understanding it seems like what ever is replaced will once again get replaced as I keep calling replace. My question is how could I do this to replace the characters in std::string all at once? I've tried making the string a constant but other than that I am stuck.
Thank you in advanced for your help!
Sep 3, 2020 at 8:13pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <string>
using namespace std;
void encode( char &c )
{
switch ( c )
{
case 'a' : c = 'e' ; return ;
case 'b' : c = 'r' ; return ;
case 'm' : c = 'a' ; return ;
}
}
int main()
{
string test = "abnormal behaviour" ;
cout << test << '\n' ;
for ( char &c : test ) encode( c );
cout << test << '\n' ;
}
A little bit more flexible:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
using namespace std;
void encode( char &c )
{
string input = "abm" ;
string output = "era" ;
size_t p = input.find( c );
if ( p != string::npos ) c = output[p];
}
int main()
{
string test = "abnormal behaviour" ;
cout << test << '\n' ;
for ( char &c : test ) encode( c );
cout << test << '\n' ;
}
Last edited on Sep 3, 2020 at 8:18pm UTC
Sep 3, 2020 at 8:26pm UTC
Thank you so much!
Sep 3, 2020 at 10:22pm UTC
Also:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
#include <algorithm>
using name space std;
int main()
{
string test = "abnormal behaviour" ;
cout << test << '\n' ;
std::transform(test.begin(), test.end(), test.begin(), [inp = "abm" s, out = "era" s, p = 0u](char ch) mutable {
return (p = inp.find(ch)) != string::npos ? out[p] : ch; });
cout << test << '\n' ;
}
giving as output:
abnormal behaviour
ernorael reheviour
Topic archived. No new replies allowed.