KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Find the position to all occurrences of specific character in a string
PRODUCT: 4D | VERSION: 14.0 | PLATFORM: Mac & Win
Published On: February 20, 2014

The Position command can be used to find the first position of a specific character in a string. Below is a method that uses the Position command to find all occurrences of a specific character in a string.

// Method name: find_ocurrences
// Returns all the occurrence of the letter "i" in the string $str as well as the
// number of occurrences. Search will be case sensitive.

C_POINTER($1;$arrPos)
C_TEXT($2;$3;$str;$search)
C_LONGINT($position;$count)
C_BOOLEAN($done)

$arrPos:=$1 // Array with the positions of all occurrences of the character
$str:=$2    // String search will be performed on
$search:=$3 // Character to be searched
$position:=0
$done:=False
While ($done=False)
  $position:=Position($search;$str;$position+1;*)
  If ($position#0)
    APPEND TO ARRAY($arrPos->$position)
  Else
    $done:=True
  End if
End while

This method will return an array that contains the positions of all the occurrences a letter inside a string.

Below is an example of how to call the method.
C_TEXT($str;$search)
ARRAY LONGINT($arrPos;0)
$str:="This is a string with many i's"
$search:="i"
find_occurrences (->$arrPos;$str;$search) // search for the all the positions of
                                          // the letter "i" in the $str