MUMPS中替换含旧字符串的新字符串时结果异常如何解决?
问题分析与解决
你的代码出现问题的核心原因是从前往后替换时,新字符串包含旧字符串,导致后续循环误匹配到刚插入的旧字符串,同时循环次数的计算逻辑也有误。
原代码中,每次替换第一个"old"为"very old"后,字符串变成"My very old old friend",下一次循环会立刻匹配到刚插入的"old",把它替换成"very old",最终得到错误结果。
正确实现方式
方式一:使用内置$REPLACE函数(推荐)
多数MUMPS实现(如InterSystems IRIS)提供了原生字符串替换函数,直接调用即可完成需求:
s str="My old old friend" s old="old" s new="very old" s str=$REPLACE(str,old,new) q str
方式二:手动从后往前替换
如果环境不支持$REPLACE,可以从字符串末尾开始向前查找替换,避免新插入的内容干扰匹配:
s str="My old old friend" s old="old" s new="very old" n pos, oldLen, newLen s oldLen=$L(old) s newLen=$L(new) ; 从字符串末尾开始找第一个匹配的old位置 s pos=$F(str,old,,-1) while pos>0 { ; 替换当前匹配的old为new s str=$E(str,1,pos-1)_new_$E(str,pos+oldLen,*) ; 向前移动位置,跳过刚替换的区域,继续查找下一个匹配 s pos=$F(str,old,pos-oldLen-1,-1) } q str
内容的提问来源于stack exchange,提问作者New27
相关产品推荐
相关产品推荐

