2

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?

0

3 Answers 3

3
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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.