KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Find number of times a pattern is found in a string
PRODUCT: 4D | VERSION: 15.1 | PLATFORM: Mac & Win
Published On: March 7, 2016

Below is an utility method for finding the number of times a pattern occurs in a string:

//Method: GET_PATTERN_COUNT
//$1 - Source string
//$2 - Pattern to search for
//$3 - Number of times pattern is found


C_TEXT($1;$2;$string;$pattern)
C_LONGINT($0;$position;$count)

If (Count parameters>=2)
   $string:=$1
   $pattern:=$2
   $count:=0
   $position:=Position($pattern;$string;$position+1;*)
   While ($position#0)
      $count:=$count+1
      $position:=Position($pattern;$string;$position+1;*)
   End while
   $0:=$count
End if


Example:
$string:="This is a test string"
$pattern:="i"

$count:=GET_PATTERN_COUNT($string;$pattern)
//$count returns 3