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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <string>
bool is_word_separator( char c )
{
static const std::string separators = " \t\n.,!?" ;
return separators.find(c) != std::string::npos ;
}
bool is_word_begin( std::string str, std::size_t pos )
{
if( str.empty() ) return false ;
if( pos == 0 ) return !is_word_separator( str[0] ) ;
return !is_word_separator( str[pos] ) && is_word_separator( str[pos-1] ) ;
}
// return position of end of word (end == one past the last character)
std::size_t word_end( std::string str, std::size_t pos )
{
while( pos < str.size() && !is_word_separator( str[pos] ) ) ++pos ;
return pos ;
}
std::size_t word_size( std::string str, std::size_t pos )
{ return is_word_begin( str, pos) ? word_end(str,pos) - pos : 0 ; }
std::size_t next_word_begin( std::string str, std::size_t pos )
{
++pos ;
while( pos < str.size() && !is_word_begin(str,pos) ) ++pos ;
return pos ;
}
std::size_t first_word_begin( std::string str )
{
std::size_t pos = 0 ;
while( pos < str.size() && !is_word_begin(str,pos) ) ++pos ;
return pos ;
}
// return true if the three words from pos start with w,t,f respectively
bool is_wtf( std::string str, std::size_t pos ) // does a look ahead
{
if( is_word_begin(str,pos) && std::tolower( str[pos] ) == 'w' )
{
pos = next_word_begin(str,pos) ;
if( pos < str.size() && std::tolower( str[pos] ) == 't' )
{
pos = next_word_begin(str,pos) ;
return pos < str.size() && std::tolower( str[pos] ) == 'f' ;
}
}
return false ;
}
// invariant: is_wtf(str,pos)
std::string replace_wtf_at( std::string str, std::size_t pos )
{
auto pt = next_word_begin(str,pos) ;
auto pf = next_word_begin( str, pt ) ;
auto cnt = pf - pos + word_size(str,pf) ;
return str.replace( pos, cnt, "WTF" ) ;
}
std::string replace_wtf( std::string str )
{
for( auto p = first_word_begin(str) ; p < str.size() ; p = next_word_begin(str,p) )
if( is_wtf(str,p) ) str = replace_wtf_at(str,p) ;
return str ;
}
|