Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / MFC

Case-Insensitive String Replace

Rate me:
Please Sign up or sign in to vote.
3.47/5 (10 votes)
25 Jan 2000CPOL 155.5K   14   25
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:

C++
// 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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Zeta Software GmbH
Germany Germany
Uwe does programming since 1989 with experiences in Assembler, C++, MFC and lots of web- and database stuff and now uses ASP.NET and C# extensively, too. He has also teached programming to students at the local university.

➡️ Give me a tip 🙂

In his free time, he does climbing, running and mountain biking. In 2012 he became a father of a cute boy and in 2014 of an awesome girl.

Some cool, free software from us:

Windows 10 Ereignisanzeige  
German Developer Community  
Free Test Management Software - Intuitive, competitive, Test Plans.  
Homepage erstellen - Intuitive, very easy to use.  
Offline-Homepage-Baukasten

Comments and Discussions

 
GeneralMore Efficient Version Pin
pwensing28-Apr-06 8:49
pwensing28-Apr-06 8:49 
While I was making some slight modifications to this for a project I was working on, I made some modifications that ended up working faster. The basic gist is that instead of performing the replace in the old string and the new string, I keep some extra track of positions so that I only need to do the replace in the main string. There was about a 27% gain in speed with this version compared to the original when I tested it (I ran it on a fairly large string 1000 times for each function). Sorry for the minor differences in parameters and such, this way suited my needs better.

void newReplace2(CString& mainStr, CString& oldStr, CString& newStr)<br />
{<br />
        //Prevent infinite loop when user tries to replace nothing.<br />
	if (oldStr != "")<br />
	{<br />
		int oldLen = oldStr.GetLength(), newLen = newStr.GetLength();<br />
		int nPos = 0, lastPos = 0, newPos = 0, posDiff = 0;<br />
<br />
                //Copies of the main string and the string to be replaced that<br />
                //are made lower case<br />
		CString mainStr_low(mainStr);<br />
		CString oldStr_low(oldStr);<br />
		mainStr_low.MakeLower();<br />
		oldStr_low.MakeLower();<br />
<br />
		while ((nPos = mainStr_low.Find(oldStr_low, nPos)) != -1)<br />
		{<br />
                        //Calc number of characters between last match and<br />
                        //new match<br />
			posDiff = nPos - lastPos;<br />
			<br />
                        //Determine the position of the match in the string<br />
                        //to be returned<br />
			newPos += posDiff;<br />
<br />
                        //Do the replace in the main string that will be<br />
                        //returned.<br />
			mainStr.Delete(newPos, oldLen);<br />
			mainStr.Insert(newPos, newStr);<br />
<br />
                        //Skip the rest of the old string<br />
			nPos += oldLen;<br />
                        //Skip the new position to the end of the new string<br />
                        //To keep it inline with the position in the old<br />
                        //string<br />
			newPos += newLen;<br />
                        //Needed to determine posDiff above<br />
			lastPos = nPos;<br />
		}<br />
	}<br />
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.