views:

240

answers:

4

Say I have a CString object strMain="AAAABBCCCCCCDDBBCCCCCCDDDAA"; I also have two smaller strings, say strSmall1="BB"; strSmall2="DD"; Now, I want to replace all occurence of strings which occur between strSmall1("BB") and strSmall2("DD") in strMain, with say "KKKKKKK"

Is there a way to do it without Regex. I cannot use regex as adding another file to the project is prohibited.

Is there a way in VC++/MFC to do it? Or any easy algorithm you can point me to?

+1  A: 

CString has a Find member function for finding the position of a substring and Left, Mid, and Right functions for extracting substrings. You can easily use these functions to extract the parts of the subject that you want to keep; then it's simply a matter of concatenation to assemble the required result.

See the MSDN page on CString for documentation.

James McNellis
A: 

psudocode:

loop over string
  if curlocation matches string strsmall1 save index break

loop over remaining string
  replace till curlocation matches string strsmall2

Extra credit:

What will the next assignment be?

My answer:

Speed it up by jumping the length of strsmall1 and strsmall2 in loop iterations

Hogan
+2  A: 
int length = strMain.GetLength();
int begin = strMain.Find(strSmall1, 0) + strSmall1.GetLength();
int end = strMain.Find(strSmall2, 0);

CStringT left = strMain.Left(begin);
CStringT right = strMain.Right(length - end);

strMain = left + "KKKKKKK" + right
John Weldon
+1  A: 

The easiest way is probably to handle the replacement recursively. Search for the starting delimiter and the ending delimiter. If you find them, put together a new string consisting of the string up to the starting delimiter, followed by the replacement string, followed by the return from recursively doing the replacement in the remainder of the string following the ending delimiter.

That, of course, assumes you want to replace all the occurrences in the main string -- if you only want to replace the first one, John Weldon's solution (for one example) will work quite nicely.

Jerry Coffin