Mumps String Replacement 函数

需要定制的函数需求

In this exercise, you’ll create a function that performs replacements in a provided string.

Create a function named strReplace(str,old,new,count):

  • str is the original string
  • old is the substring in str to be replaced
  • new is the string that will replace old
  • count is an output parameter that counts the number of replacements
  • Quit from strReplace with the updated string

Keep in mind that new could contain old. You should account for this when designing your solution. Be sure to avoid infinite loops.

测试用例

1 - Replaces a single instance
  *Test: s result=$$strReplace^XCHR310EX2YCH("My old friend","old","new",.count)
  *result has been incorrectly set to 1 but expected "My new friend"

2 - Replaces multiple instances
  *Test: s result=$$strReplace^XCHR310EX2YCH("My old old
    friend","old","new",.count)
  *result has been incorrectly set to 1 but expected "My new new friend"

3 - Replaces longer strings
  *Test: s result=$$strReplace^XCHR310EX2YCH("My archaic archaic
    friend","archaic","old",.count)
  *result has been incorrectly set to 1 but expected "My old old friend"

4 - Replaces shorter strings
  *Test: s result=$$strReplace^XCHR310EX2YCH("My old old
    friend","old","archaic",.count)
  *result has been incorrectly set to 1 but expected "My archaic archaic friend"

5 - Replaces with replaced string
  *Test: s result=$$strReplace^XCHR310EX2YCH("My old old
    friend","old","old",.count)
  *result has been incorrectly set to 1 but expected "My old old friend"

6 - Replaces with a string that includes the replaced string
  *Test: s result=$$strReplace^XCHR310EX2YCH("My old old friend","old","very
    old",.count)
  *result has been incorrectly set to 1 but expected "My very old very old
    friend"

源代码

 N I
 N TOK
 N OSTR
 SET count=0
 F I=1:1:$L(str," ") S TOK=$P(str," ",I) S:TOK=old TOK=new S:TOK=new count=count+1 S OSTR=$G(OSTR)_" "_TOK
 QUIT $E(OSTR,2,$LENGTH(OSTR))