#pragma warning( disable: 4786 )
#include <cassert>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
bool
IsWhiteSpace( char c )
{
return ( (c == ' ') || (c == '\t') ||
(c == '\r') || (c == '\n') );
}
void
Tokenize( vector<string>& strings,
const string& fullString )
{
string::size_type pos = 0;
string::size_type size = fullString.size();
string temp;
// Skip whitespace at beginning.
for ( ; pos < size; ++pos )
{
if ( IsWhiteSpace( fullString[ pos ] ) == true )
{
temp += fullString[ pos ];
}
else
{
break;
}
}
if ( temp.size() > 0 )
{
strings.push_back( temp );
temp.erase();
}
// Now put each word into the vector.
string::size_type wordStart = pos;
bool val = true;
for ( ; pos < size; ++pos )
{
if ( IsWhiteSpace( fullString[ pos ] ) == val )
{
// Add the word or whitespace to the vector.
strings.push_back( fullString.substr( wordStart, pos - wordStart ) );
wordStart = pos;
val = !val;
}
}
if ( pos > wordStart )
{
strings.push_back( fullString.substr( wordStart, pos - wordStart ) );
}
}
void
Replace( string& str,
string::iterator start,
string::iterator end,
string& oldStr,
string& newStr )
{
string temp( start, end );
vector<string> strings;
Tokenize( strings, temp );
temp.erase();
unsigned int size = strings.size();
for ( unsigned int index = 0; index < size; ++index )
{
if ( strings[ index ] == oldStr )
{
temp += newStr;
}
else
{
temp += strings[ index ];
}
}
str.replace( start, end, temp );
}
int main()
{
string test( "One and two and three" );
cout << test << endl;
string oldStr( "and" );
string newStr( "or" );
Replace( test, test.begin(), test.end(), oldStr, newStr );
cout << test << endl;
return 0;
}