KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method to find the Nth instance of a string in a document
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: June 5, 2023

You can use the following method, which utilizes file handles, to find the Nth instance of a phrase in a file/document:

findNthInstance Method

// Find Nth Instance Method
// uses a file handle to find the Nth instance of a phrase ($stopChar) in a document
// if found, returns index of the phrase
// if not found, returns -1

// declare parameters
#DECLARE($file : Object; $stopChar : Text; $n : Integer)->$index : Integer

// declare variables
var $stopChar; $line : Text
var $file; $fileHandle : Object
var $n; $index : Integer


// first check that $stopChar is a non-empty string
If ($stopChar#"")
   // open read handle
   $fileHandle:=$file.open("read")
  
   // corner case: N = 1, stopChar is found at beginning of file
   // (has same conditions as stopChar not found in file)
   $line:=$fileHandle.readLine()
   If (Substring($line; 0; Length($stopChar))=$stopChar)
     return 0
   End if
  
   // for N loops, use readText() function
   // if there are less than N instances of $stopChar, break the loop and return -1 (not found)
   For ($i; 1; $n)
     // use readText() function
     $text:=$fileHandle.readText($stopChar)
    
     // find stopChar in file
     Case of
     // stopChar is in middle/at end of file (general case)
     : ($text#"")
       // set output to "Text_readHandleOutput" text field on form
       $index:=$fileHandle.offset
      
       // increment to set offset after first letter of found phrase
       $fileHandle.offset:=$fileHandle.offset+1
      
       // stopChar is not in file at all
     : ($text="")
       return -1
     End case
    
     // return index of Nth instance of $stopChar
     If ($i=$n)
     // decrement to return index of first letter of last found phrase
       return $index-1
     End if
   End for
End if



Tester Method
// Tester Method
// tests the "findNthInstance" method

// declare variables
var $path; $stopChar : Text
var $file : Object
var $index : Integer

// import document as file object in 4D
$path:=Get 4D folder(Current resources folder)+"FoxInSocks.txt"
$file:=File($path; fk platform path)

// test findNthInstance
// ex: find the 2nd instance of "socks" in "FoxInSocks.txt"
$index:=findNthInstance($file; "Fox"; 2)