Hi Mike.
| | > On Tue, 10 Feb 2004 00:21:02 GMT, "Cy Edmunds"
| >
| > >std::string // replace all instances of victim with replacement
| > >mass_replace(const std::string &source, const std::string &victim, const
| > >std::string &replacement)
| > >{
| > > std::string answer = source;
| > > std::string::size_type j = 0;
| > > while ((j = answer.find(victim, j)) != std::string::npos )
| > > answer.replace(j, victim.length(), replacement);
| > > return answer;
| > >}
| >
| > This function doesn't work.
| >
| > mass_replace("a", "a", "a");
| >
| > Oops.
|
| Try mine, I spent a bit of time testing it for such corner cases
| (since I needed to write something like that for myself anyway).
|
| Of course I might have missed something...
Since you're interested in such an exercise for yourself,
then I thought the following might interest you too ;-):
# include <iostream>
# include <ostream>
# include <string>
inline std::string TrimBS( const std::string& S,
const std::string& Junk = " \a\b\f\t\n\r\v," )
{
const std::string::size_type First( S.find_first_not_of( Junk ) );
const std::string::size_type Last( S.find_last_not_of( Junk ) );
return ( First == std::string::npos ) ?
std::string( "" ) : S.substr( First, Last - First + 1 );
}
inline void ReplaceTokens( std::string& S, const std::string& Token )
{
S = TrimBS( S );
std::string::size_type Idx( 0 );
std::string::size_type Pos( 0 );
std::string::size_type Start( 0 );
static const char* GoodChars( "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
while( ( Pos = S.find_first_not_of( GoodChars, Start ) ) != std::string::npos )
{
if( ( Idx = S.find_first_of( GoodChars, Pos ) ) != std::string::npos )
{
S.erase( Pos, Idx - Pos );
S.insert( Pos, Token );
}
Start = Pos + Token.size();
}
}
int main()
{
std::string S( " A , B, C , D,Z, " );
std::cout << S << std::endl;
ReplaceTokens( S, " or " );
std::cout << S << std::endl;
return 0;
}
-- Input --
A , B, C , D,Z,
-- Output --
A or B or C or D or Z
Cheers.
Chris Val