Varun Mahajan
Varun Mahajan

Reputation: 7297

How to replace a string between two substrings in a string in VC++/MFC?

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?

Upvotes: 2

Views: 1521

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490318

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.

Upvotes: 1

John Weldon
John Weldon

Reputation: 40789

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

Upvotes: 3

Hogan
Hogan

Reputation: 70529

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

Upvotes: 1

Related Questions