Old Wolf posted:
I have two strings of corresponding characters, for example:
s1 = "abc"
s2 = "XYZ"
Is there an algorithm so that whenever a character from S1 occurs
in a string, it is replaced by the corresponding character from S2?
eg. running "crabs" through this function will producs "ZrXYs".
I'm doing this just for the fun of it. If it's your homework, then in the
long run, you won't gain from copy-pasting my code... all it takes is one
exam to demonstrate your inability.
#include <cassert>
#ifndef NDEBUG
#include <cstring>
#endif
void SmartReplace( char *p,
const char * const check_for,
const char * const replace_with )
{
assert( std::strlen(replace_with) >= std::strlen(check_for) );
for( ; *p; ++p )
{
const char *p_check = check_for;
const char *p_replace = replace_with;
for( ; *p_check; ++p_check, ++p_replace )
{
if ( *p == *p_check ) *p = *p_replace;
}
}
}
#include <iostream>
#include <cstdlib>
int main()
{
using std::cout;
char str[] = "crabs";
SmartReplace( str, "abc", "XYZ" );
cout << str << '\n';
std::system("PAUSE");
}
--
Frederick Gotham