1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <string>
#include <cstring>
See: https://cal-linux.com/tutorials/strings.html
bool replace( std::string& inwhat, const std::string& what, const std::string& withwhat )
{
const auto pos = inwhat.find(what) ;
if( pos == std::string::npos ) return false ;
inwhat.replace( pos, what.size(), withwhat ) ;
return true ;
}
std::size_t replace_all( std::string& inwhat, const std::string& what, const std::string& withwhat )
{
std::size_t cnt = 0 ;
if( !what.empty() )
{
for( auto pos = inwhat.find(what) ; pos != std::string::npos ; ++cnt)
{
inwhat.replace( pos, what.size(), withwhat ) ;
pos = inwhat.find( what, pos + withwhat.size() ) ;
}
}
return cnt ;
}
// invariant: arguments are not null, inwhat is large enough to hold the replacement
void replace( char* inwhat, const char* what, const char* withwhat )
{
std::string str = inwhat ;
if( replace( str, what, withwhat ) ) std::strcpy( inwhat, str.c_str() ) ;
}
// invariant: arguments are not null, inwhat is large enough to hold the replacement
void replace_all( char* inwhat, const char* what, const char* withwhat )
{
std::string str = inwhat ;
if( replace_all( str, what, withwhat ) ) std::strcpy( inwhat, str.c_str() ) ;
}
|