My code is:
#include <windows.h>
#include <iostream>
using namespace std;
struct ReplacementFlags
{
public:
bool rfReplaceAll, rfIgnoreCase;
ReplacementFlags(bool ReplaceAll = false, bool IgnoreCase = false) : rfReplaceAll(ReplaceAll), rfIgnoreCase(IgnoreCase) {}
~ReplacementFlags() {}
ReplacementFlags& operator ()(bool ReplaceAll = false, bool IgnoreCase = false)
{
if((rfReplaceAll != ReplaceAll) && (rfIgnoreCase != IgnoreCase))
{
rfReplaceAll = ReplaceAll;
rfIgnoreCase = IgnoreCase;
}
return *this;
}
private:
bool operator == (const ReplacementFlags &RF) const
{
return ((rfReplaceAll == RF.rfReplaceAll) && (rfIgnoreCase == RF.rfIgnoreCase));
}
bool operator != (const ReplacementFlags &RF) const
{
return !((rfReplaceAll == RF.rfReplaceAll) && (rfIgnoreCase == RF.rfIgnoreCase));
}
};
string ToLower(string Str)
{
for (int I = 0; I < Str.size(); I++)
if(Str[I] >= 0x41 && Str[I] <= 0x5A)
Str[I] = Str[I] + 0x20;
return Str;
}
string Replace(string Text, string FindStr, string ReplacementString, ReplacementFlags Flags)
{
size_t Pos = 0;
string TempStr = Text;
string TempFind = FindStr;
if (!Flags.rfReplaceAll)
{
if (Flags.rfIgnoreCase)
{
TempStr = ToLower(Text);
TempFind = ToLower(FindStr);
}
Pos = TempStr.find(TempFind);
if (Pos != string::npos)
Text.replace(Pos, FindStr.size(), ReplacementString);
}
else
{
if (Flags.rfIgnoreCase)
{
TempStr = ToLower(Text);
TempFind = ToLower(FindStr);
}
Pos = TempStr.find(TempFind);
while (Pos != string::npos)
{
Text.replace(Pos, FindStr.size(), ReplacementString);
Pos = TempStr.find(TempFind, Pos + 1);
}
}
return Text;
}
int main()
{
cout<<Replace("Bleh Is Cool, Is Cool, Is Cool", "Cool", "Meh", ReplacementFlags(true, true));
cin.get();
return 0;
}
The problem occurs after the Else..
if (Flags.rfIgnoreCase)
{
TempStr = ToLower(Text);
TempFind = ToLower(FindStr);
}
Pos = TempStr.find(TempFind);
while (Pos != string::npos)
{
Text.replace(Pos, FindStr.size(), ReplacementString);
Pos = TempStr.find(TempFind, Pos + 1); //Problem at this line.. Changing it to Text.find instead of TempStr.find makes it work :S EXCEPT that it stops finding non-casesensitive strings.
}
Any ideas what's wrong? both the strings are the same length and size.. only difference is one is uppercase the other is lower..