Replace (String function)

From m204wiki
Revision as of 21:05, 5 November 2012 by JAL (talk | contribs) (→‎Examples)
Jump to navigation Jump to search

Replace occurrences of a substring with a substitute string (String class)

The Replace intrinsic function replaces one, or multiple, occurrences of a substring within the method object input string with a substitute string, returning the modified version of the input string.

Syntax

%outString = string:Replace( substring, replacement, [Count= number])

Syntax terms

%outString A string variable to receive the modified input string.
string The string to which the method is applied.
substring The substring that the method attempts to replace in the input string. If string contains no occurrences of substring, %outstring is set to a copy of string. If substring is null or longer than 255 characters, the request is cancelled.
replacement A string that contains the characters that replace the specified substring. If replacement is:
  • not specified, %outstring is set to a copy of string;
  • longer than 255 characters, the request is cancelled;
  • null, the substring characters are removed from string.
Count An optional, but name required, argument that is the number of occurrences of substring to replace. Only values greater than 0 are valid. If count is:
  • less than the number of occurrences of the substring, only the first count occurrences are substituted.
  • greater than or equal to the number of occurrences of the substring, all occurrences of the given substring are substituted.
  • not specified, all occurrences are substituted.

Usage notes

  • The search for the target substring is context sensitive; case matters in the attempt to find, as well as in the replacement of, the target characters.
  • Calling Replace with an empty replacement string argument is equivalent to using Remove.
  • Replace is available as of Sirius Mods Version 7.3.

Examples

The following request shows two examples of Replace calls against the same input string: the first call replaces two occurrences of a specified substring; the second removes all occurrences of a different substring.

begin %x is longstring %substr is string len 6 %repl is string len 2 %out is longstring %x = 'How much wood would a woodchuck chuck' %substr = 'wo' %repl = '?' %out = %x:replace(%substr, %repl, Count=2) printText {~} is {%out} %substr = ' wood' %repl = '' %out = %x:replace(%substr, %repl) printText {~} is {%out} end

The request output follows:

%out is How much ?od ?uld a ?odchuck chuck %out is How much would achuck chuck

See also