KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Getting the Position of a String in a Blob
PRODUCT: 4D | VERSION: 2003 | PLATFORM: Mac & Win
Published On: June 17, 2004

The string command position lets you find the exact location of the first character of a matching string. However, the limitation of the text type is 32K characters. So if you want to search through a file, you might have to open the document as a blob and break it up into smaller chunks of text.

This might not be the best approach because the string you are trying to search for might be broken up between blobs, so you might never find the string even if it is there!

The better solution then, is to search directly in a blob for the string. The following method called FindInBlob, will find a matching string in a blob and return its position in the blob:

C_BLOB($1;$blob)
C_TEXT($2;$searchString)
C_LONGINT($0;$location;$i;$searchIndex;$offset;$ascii)

$blob:=$1
$searchString:=$2
$searchIndex:=1
$location:=-1

If (Length($searchString)>0)
  For ($offset;0;BLOB size($blob)-1)

    For ($i;$offset;BLOB size($blob)-1)

      $ascii:=$blob{$i}

      If($ascii=Ascii($searchString[[$searchIndex]]))
       $searchIndex:=$searchIndex+1
      Else
       $searchIndex:=1
      End if

      If ($searchIndex>Length($searchString))
       $location:=$i-($searchIndex-2)
       $i:=BLOB size($blob)
      End if

    End for

    If($location#-1)
      $offset:=BLOB size($blob)
    End if

  End for
End if

$0:=$location


Suppose you had a blob of text of the text string "Hello, World!":

C_BLOB($myBlob)
DOCUMENT TO BLOB("mytext.txt";$myBlob)

C_LONGINT($position)
$position:=FindInBlob($myBlob;"World")

The result of $position would then be 7 (blob indices start at 0).