PositionIn and PositionOf (String functions)

From m204wiki
Revision as of 20:08, 26 January 2011 by Alex (talk | contribs)
Jump to navigation Jump to search

The position of one string inside another (String class)


These functions return the numeric position of the first occurrence of one string inside another. The difference between the two methods is that for PositionIn, the method object string is located in the first argument string, whereas for PositionOf, the first argument string is located in the method object string. Which is more convenient to use will be application dependent.

These functions are available as of version 7.2 of the Sirius Mods.

Syntax

%position = string:PositionIn( haystack, [Start= number])

%position = string:PositionOf( needle, [Start= number])

Syntax terms

%pos A variable to receive the position of the first occurrence of the needle string in the haystack string, starting at the implicit or explicit starting position. If needle is not found in haystack, spos is set to 0.
needle The string to be located in the haystack string.
haystack The string in which needle is to be located.
Start=spos This optional, name-required argument is a number that specifies the position in the haystack string at which to start searching for the needle string. spos defaults to 1, meaning that the search begins at the first character in haystack.

Usage notes

  • The starting position must be a positive number. A zero or negative number results in request cancellation. Specifying a starting position greater than the length of (haystack plus one minus the length of needle) returns a zero, because there are not enough characters in haystack to satisfy the search.
  • The PositionOf and PositionIn methods do exactly the same thing. The only difference between them is that in PositionOf, the haystack is the method object and the needle is the first argument. In PositionIn, the method object and first argument are reversed. Which method is preferable will depend on the application, and, in many cases, it will be quite arbitrary which one is used.
  • The PositionOf and PositionIn methods are the object-oriented equivalents of the User Language $index function.

Examples

  • If '%s' contains "This is a test", the following statements
   printText {%s:positionOf('is')}
   printText {%s:positionOf('is', start=4)}
   printText {%s:positionOf('is', start=7)}

will display

   3
   6
   0
  • If '%s' contains "ver", the following statements
   printText {%s:positionIn('Never say never')}
   printText {%s:positionIn('Never say never', start=4)}
   printText {%s:positionIn('Never say never', start=14)}

will display

   3
   13
   0

See also

List of intrinsic String methods