如何在 VC++/MFC 中的字符串中的两个子字符串之间替换字符串? [英] How to replace a string between two substrings in a string in VC++/MFC?

查看:73
本文介绍了如何在 VC++/MFC 中的字符串中的两个子字符串之间替换字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 CString 对象 strMain="AAAABBCCCCCCDDBBCCCCCCDDDAA";我还有两个较小的字符串,比如 strSmall1="BB";strSmall2="DD";现在,我想替换 strMain 中 strSmall1("BB") 和 strSmall2("DD") 之间出现的所有字符串,比如KKKKKKK"

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.

VC++/MFC 有没有办法做到这一点?或者您可以指出任何简单的算法?

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

推荐答案

最简单的方法可能是递归处理替换.搜索起始定界符和结束定界符.如果找到它们,则将一个新字符串放在一起,该字符串由起始分隔符之前的字符串组成,然后是替换字符串,然后是递归地在结束分隔符之后的字符串的其余部分中进行替换的返回.

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.

当然,这假设您想替换主字符串中的所有出现 - 如果您只想替换第一个,John Weldon 的解决方案(例如)将非常有效.

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.

这篇关于如何在 VC++/MFC 中的字符串中的两个子字符串之间替换字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆