Returns an INTEGER value that indicates the position of a search string within a source string.
The starting position is in characters if source is a CHARACTER or LONGCHAR expression. The starting position is in bytes if source is a MEMPTR.
For this example, you must enter 1, 2, 3, 4, or 5. The INDEX function checks if the digit exists in the string "12345".
r-index.p
DEFINE VARIABLE x AS CHARACTER NO-UNDO FORMAT "9" LABEL "Enter a digit between 1 and 5". DEFINE VARIABLE show AS CHARACTER NO-UNDO FORMAT "x(5)" EXTENT 5 LABEL "Literal" INITIAL ["One", "Two", "Three", "Four", "Five"]. REPEAT: SET x AUTO-RETURN. IF INDEX("12345",x) = 0 THEN DO: MESSAGE "Digit must be 1,2,3,4, or 5. Try again.". UNDO, RETRY. END. ELSE DISPLAY show[INTEGER(x)]. END. |
This procedure also uses the starting option:
r-index2.p
DEFINE VARIABLE positions AS CHARACTER NO-UNDO FORMAT "x(60)". DEFINE VARIABLE sentence AS CHARACTER NO-UNDO FORMAT "x(72)". DEFINE VARIABLE vowel AS CHARACTER NO-UNDO FORMAT "x". DEFINE VARIABLE found AS INTEGER NO-UNDO. DEFINE VARIABLE loop AS INTEGER NO-UNDO. DEFINE VARIABLE start AS INTEGER NO-UNDO. FORM sentence LABEL "Type in a sentence" WITH FRAME top TITLE "This program will tell where the vowels are in a sentence.". SET sentence WITH FRAME top. DO loop = 1 TO 5: ASSIGN positions = "" vowel = SUBSTRING("aeiou",loop,1) start = 1 found = INDEX(sentence,vowel,start). DO WHILE found > 0: ASSIGN positions = positions + STRING(found) + " " start = found + 1 found = INDEX(sentence,vowel,start). END. DISPLAY vowel LABEL "Vowel" positions LABEL "Is found at locations..." WITH 5 DOWN. DOWN. END. |
The following example demonstrates using the INDEX function on a MEMPTR variable:
DEFINE VARIABLE mptr AS MEMPTR NO-UNDO. DEFINE VARIABLE str AS CHAR NO-UNDO. DEFINE VARIABLE str1 AS CHAR CASE-SENSITIVE NO-UNDO. str = "Using MEMPTR as source param. MEMPTR is an ABL data type" . SET-SIZE(mptr) = LENGTH(str, "raw") + 1. PUT-STRING(mptr, 1) = str. MESSAGE INDEX(mptr, "memptr", 10). // returns 31 str1 = "memptr". MESSAGE INDEX(mptr, str1, 10). // returns 0 |