简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM