next up previous contents index
Next: LEN Up: Character Intrinsic Functions Previous: CHAR and ICHAR

INDEX

INDEX is a search function; it takes two character arguments and returns an integer result. INDEX(S1, S2) searches for the character-string S2 in another string S1, which is usually longer. If S2 is present in S1 the function returns the character position at which it finds starts. If there is no match (or S1 is shorter than S2) then it returns the value zero. For example:

 
      CHARACTER*20 SPELL 
      SPELL  = 'ABRACADABRA' 
      K      = INDEX(SPELL, 'RA')
Here K will be set to 3 because this is the position of the first occurrence of the string 'RA'. To find the second occurrence it is necessary to restart the search at the next character in the main string, for example:
L = INDEX(SPELL(K+1:), 'RA')
This will return the value 7 because the first occurrence of 'RA' in the substring 'ACADABRA' is at position 7. To find its position in the parent string the offset, K, must be added, making 10.

The INDEX function is often useful when manipulating character information. Suppose, for example, we have an string NAME containing the a person's surname and initials, e.g.
Mozart,W.A
The name can be reformatted to put the initials before the surname and omit the comma like this:

 
      CHARACTER NAME*25, PERSON*25 
*... 
      KCOMMA = INDEX(NAME, ',') 
      KSPACE = INDEX(NAME, ' ') 
      PERSON = NAME(KCOMMA+1:KSPACE-1) // NAME(1:KCOMMA-1)
Then PERSON will contain the string 'W.A.Mozart' (with blanks appended to the length of 25). Note that a separate variable, PERSON, was necessary because of the rule about overlapping strings in assignments.


next up previous contents index
Next: LEN Up: Character Intrinsic Functions Previous: CHAR and ICHAR
Helen Rowlands
8/27/1998