Case-Insensitive String Replace
Function to replace all occurences of a string within another, ignoring the case
Introduction
This is a simple function that acts like CString::Replace()
, except that the case of the string to search for is ignored.
The whole code follows:
// instr: string to search in.
// oldstr: string to search for, ignoring the case.
// newstr: string replacing the occurrences of oldstr.
CString ReplaceNoCase( LPCTSTR instr, LPCTSTR oldstr, LPCTSTR newstr )
{
CString output( instr );
// lowercase-versions to search in.
CString input_lower( instr );
CString oldone_lower( oldstr );
input_lower.MakeLower();
oldone_lower.MakeLower();
// search in the lowercase versions,
// replace in the original-case version.
int pos=0;
while ( (pos=input_lower.Find(oldone_lower,pos))!=-1 ) {
// need for empty "newstr" cases.
input_lower.Delete( pos, lstrlen(oldstr) );
input_lower.Insert( pos, newstr );
// actually replace.
output.Delete( pos, lstrlen(oldstr) );
output.Insert( pos, newstr );
}
return output;
}
The function's implementation is rather simple: it creates several copies of the strings. If you need a memory- and speed- optimized replace function, this one is probably not the best for you. Anyway, in my project, it worked just well.
Please feel free to ask any questions you have by e-mail: keim@zeta-software.de.
History
- 25th January, 2000: Initial post