Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Case-Insensitive String Replace

0.00/5 (No votes)
25 Jan 2000 2  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here