New27
New27

Reputation: 39

How to replace string in MUMPS where new string consist of old string?

trying to write a code in MUMPS to replace old with new in a string. However new contain old.

Expected answer ="My very old very old friend" But Got = "My very very old old friend" instead How do i get the expected answer?

s str="My old old friend"
s old="old"
s new="very old" 
n ctr,max
s max=$L(str)
f ctr=1:1:($L(str,$E(old))-1) i $F(str,old)>0 s $E(str,$F(str,old)-$L(old),$F(str,old)-1)=new s count=count+1
q str

Upvotes: -1

Views: 265

Answers (1)

igotmumps
igotmumps

Reputation: 614

I think the issue you are having is that you are modifying str in place. So the first "old" gets replaced with "very old". Then the $F sees the "old" from "very old" and replaces it.

  1. My old old friend. <-- first "old" is replaced
  2. My very old old friend <-- then the "old" in "very old" is replaced.
  3. My very very old old friend

You are better off creating a new string to return instead of modifying in place. Here is what I came up with:

S STR="My old old friend"
S OLD="old"
S NEW="very old"
F I=1:1:$L(STR," ") S TOK=$P(STR," ",I) S:TOK=OLD TOK=NEW S OSTR=$G(OSTR)_" "_TOK
W OSTR,!

Upvotes: 2

Related Questions