INSTR - QB64 Wiki


From QB64 Wiki

Jump to: navigation, search

The INSTR function searches for the first occurance of a search STRING within a string and returns the position it was found.


position% = INSTR([start%,] basestring$, searchstring$)


  • The literal or variable INTEGER start of search character position of the basestring is optional.
  • The basestring is the literal or variable STRING value to be searched for an exact match including letter cases.
  • The searchstring is the literal or variable STRING value to find an exact match of in the basestring.


  • The start position must be at least 1 or greater when used or there will be an Illegal function call error.
  • The basestring position of the first character of the searchstring is returned by the function when found.
  • Position returned will be 0 if the search found no matches in the base string.
  • Function always returns 0 with an empty basestring and returns 1 with an empty searchstring!
  • The Start position is useful when making multiple searches in the same string. Otherwise it starts at the beginning!
  • The searchstring should be smaller or equal in length to the basestring. Otherwise function returns zero!
  • Non-zero position return values can be used as a new start position by adding 1 to re-search the base string.
  • In a loop, INSTR can search an entire file for occurences of certain words. See the MID$ statement example.

Example: Reading more than one instance of a word in a string using the INSTR return value as the start value plus 1.

text$ = "The cats and dogs where playing, even though dogs don't like cats." DO findcats% = INSTR(findcats% + 1, text$, "cats") ' find another occurance after IF findcats% THEN PRINT "There is 'cats' in the string at position:"; findcats% LOOP UNTIL findcats% = 0 findmonkey% = INSTR(text$, "monkeys") ' find any occurance? PRINT findmonkey%; "'monkeys' were found so it returned:"; findmonkey%

There is 'cats' in the string at position: 5 There is 'cats' in the string at position: 62 0 'monkeys' were found so INSTR returned: 0

Explanation: When the INSTR return value is 0 there are no more instances of a string in a string so the search loop is exited.

See also:

Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page
Personal tools