home *** CD-ROM | disk | FTP | other *** search
/ DP Tool Club 24 / CD_ASCQ_24_0995.iso / vrac / homonlib.zip / RINSTR.BAS < prev    next >
BASIC Source File  |  1995-04-13  |  2KB  |  49 lines

  1. DEFINT A-Z
  2.  
  3. DECLARE FUNCTION Rinstr (start, search$, lookfor$)
  4.  
  5. FUNCTION Rinstr (start, search$, lookfor$)
  6. '****************************************************************************
  7. 'Kind of a "Reverse INSTR" (hence the name).  Returns the character position
  8. ' of the LAST occurrence of a substring within another.
  9. '
  10. 'If the start argument is greater than zero, search$ is truncated to
  11. ' (start-1) before the search begins (I would rather have called it "end" but
  12. ' that word is taken).  The start argument is especially useful for
  13. ' subsequent calls to Rinstr, i.e., to find the second-to-last occurrence,
  14. ' etc.
  15. '
  16. 'Examples:  Rinstr(0,"Peter Piper","er")  --> 10
  17. '           Rinstr(10,"Peter Piper","er") --> 4  (Searches "Peter Pip")
  18. '
  19. '****************************************************************************
  20.  
  21. IF search$ = "" OR lookfor$ = "" THEN   'If either argument is a null string,
  22.      Rinstr = 0                         'return zero.  (I hate that INSTR
  23.      EXIT FUNCTION                      'returns a 1 when you search for a
  24. END IF                                  'null string!)
  25.  
  26. IF start > LEN(search$) OR start < 0 THEN    'Return zero if start is greater
  27.      Rinstr = 0                              'than the length of search$ or
  28.      EXIT FUNCTION                           'is negative.
  29. END IF
  30.  
  31. IF start > 0 THEN                       'If start > 0, chop the string at
  32.      s$ = LEFT$(search$, start - 1)     'that position so we don't bother
  33. ELSE                                    'searching past it.
  34.      s$ = search$                       'Otherwise, just use the original.
  35. END IF
  36.  
  37. last = 0
  38. x = INSTR(s$, lookfor$)                      'Get the first occurrence.
  39.  
  40. WHILE x > 0                                  'Go through the string,
  41.      last = x                                'increasing the starting
  42.      x = INSTR((last + 1), s$, lookfor$)     'position each time the
  43. WEND                                         'substring is found.
  44.  
  45. Rinstr = last            'Return the position of the rightmost occurrence.
  46.  
  47. END FUNCTION
  48.  
  49.