Questa routine che ho scritto un po' di tempo fa dovrebbe gestire tutti i possibili casi.
codice:
//Replaces all the instances of search with replace in string; returns the number of substitutions done
unsigned int ReplaceString(std::string & string,const std::string & search,const std::string & replace)
{
	unsigned int ret=0;
	for(std::string::size_type pos=string.find(search);pos!=string.npos;ret++,pos=string.find(search,++pos))
	{
		if(search.length()>replace.length())
			string.erase(pos,search.length()-replace.length());
		if(search.length()<replace.length())
			string.insert(pos,replace.length()-search.length(),_T(' '));
		string.replace(pos,replace.length(),replace);
	}
	return ret;
}