INDEX Function

The INDEX function searches through a string for a specified substring and returns the starting column position of the substring.

Format

INDEX(string,substring,n)

Parameter(s)

string

An expression evaluating to the string to be searched through.

substring

An expression evaluating to the substring to be searched for.

n

An expression evaluating to the occurrence of the substring to search for.

Description

The INDEX function returns the starting column position for a specified occurrence of a substring in a string.

If the nth occurrence of the substring is found within the string, the starting column position of the substring is returned. If substring is null, 1 is returned. If the specified occurrence of the substring cannot be found, a value of zero is returned.

Examples

If the string STRING contains NOW IS THE TIME, to assign the variable POS to the third word (THE) begins on, the code would read:

EQU BLANK TO ""

   .

   .

   .

POS = INDEX(STRING, BLANK, 3)

In this instance POS would contain 8.

In the next application the INDEX function is used within a global change of a string. The COUNT function is used to return the number of times the string occurs, and the LEN function is used to determine the length of the original string. Within a FOR...NEXT loop, the INDEX function returns the column at which the string next occurs, and the substring assignment statement is used to replace the original string with the new string.

PRINT "GLOBAL CHANGE : "        

PRINT                

PRINT "STRING TO CHANGE : " :      

INPUT ORIG.STR            

PRINT "CHANGE TO : " :         

INPUT NEW.STR            

NO.OF.OCCURS  =  COUNT(RECORD, ORIG.STR)

LENGTH  =  LEN(ORIG.STR)        

FOR I = 1 TO NO.OF.OCCURS       

   POS = INDEX(RECORD, ORIG.STR , 1)   

   RECORD[POS, LENGTH]= NEW.STR   

NEXT I           

In the next example the INDEX function is used with a formatted screen menu. In the ON... GOSUB statement, the INDEX function returns a 1, 2, or 3, which forces a branch to the first, second, or third subroutine listed.

EQUATE TRUE TO 1 , FALSE TO 0                 

PRINT @(-1) : @(4 , 4) : "WOULD YOU LIKE TO : " :           

PRINT @(4 , 7) : "ADD A RESERVATION : " :              

PRINT @(4 , 8) : "CHANGE A RESERVATION : " :            

PRINT @(4 , 9) : "REMOVE A RESERVATION : " :            

PRINT @(0 , 23) : "ENTER A , C OR R : " :              

LOOP                             

   VALID = TRUE

   PRINT @(18 , 23) : @(-4) :                   

   INPUT CHAR , 1 :                       

   IF COUNT("ACR" , CHAR) <> 1 THEN

      VALID = FALSE                      

   END

UNTIL VALID DO REPEAT                    

ON INDEX("ACR" , CHAR , 1) GOSUB ADD , CHANGE ,

REMOVE

   .

   .

   .

See Also

Statement and Function Reference