Finds a substring by value and returns an integer specifying its end position in the string.
Description
$FIND returns an integer specifying the end position of a substring within a string. $FIND searches string for substring. $FIND is case-sensitive. If substring is found, $FIND returns the integer position of the first character following substring. If substring is not found, $FIND returns a value of 0.
Because $FIND returns the position of the character following the substring, when substring is a single character that matches the first character of string $FIND returns 2. When substring is the null string (""), $FIND returns 1.
You can include the position option to specify a starting position for the search. If position is greater than the number of characters in string, $FIND returns a value of 0.
$FIND counts characters, not bytes. Therefore, it can be used with strings containing 8-bit or 16-bit (Unicode) characters. For further details on InterSystems IRIS Unicode support, refer to Unicode in Using ObjectScript.
Examples
For example, if variable var1 contains the string “ABCDEFG” and variable var2 contains the string “BCD,” the following $FIND returns the value 5, indicating the position of the character (“E”) that follows the var2 string:
SET var1="ABCDEFG",var2="BCD"
WRITE $FIND(var1,var2)
The following example returns 4, the position of the character immediately to the right of the substring “FOR”.
SET X="FOREST"
WRITE $FIND(X,"FOR")
In the following examples, $FIND searches for a substring that is not in string, for a null substring, and for a substring that is the first character of string. The examples return 0, 1, and 2, respectively:
WRITE !,$FIND("aardvark","z") ; returns 0
WRITE !,$FIND("aardvark","") ; returns 1
WRITE !,$FIND("aardvark","a") ; returns 2
The following examples show what happens when string is a null string:
WRITE !,$FIND("","z") ; returns 0
WRITE !,$FIND("","") ; returns 1
The following example returns 14, the position of the character immediately to the right of the first occurrence of “R” after the seventh character in X.
SET X="EVERGREEN FOREST",Y="R"
WRITE $FIND(X,Y,7)
In the following example, $FIND begins its search after the last character in string. It returns zero (0):
SET X="EVERGREEN FOREST",Y="R"
WRITE $FIND(X,Y,20)
The following example uses $FIND with $REVERSE to perform a search operation from the end of the string. This example locates the last example of a string within a line of text. It returns the position of that string as 33:
SET line="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
SET position=$LENGTH(line)+2-$FIND($REVERSE(line),$REVERSE("THE"))
WRITE "The last THE in the line begins at ",position
The following example uses name indirection to return 6, the position of the character immediately to the right of the substring “THIS”:
SET Y="x",x="""THIS IS A TEST"""
WRITE $FIND(@Y,"THIS")
For more information, see the Indirection Operator reference page.