KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Getting string tokens into an array
PRODUCT: 4D | VERSION: | PLATFORM: Mac & Win
Published On: June 4, 2002

Compatibility: 6.5.x , 6.7.x, and 6.8.x

Here is a project method that extracts from a string all the substrings that are separated by a separator (such as ;, &, @ and etc.) and stores them into an array.

` Project Method: GetStringToken
` $1 - Text to be extracted
` $2 - Separator Character
` $3 - Pointer to an array
` Author: Add Komoncharoensiri - 4D, Inc.

C_TEXT($1;$2;$string;$Separator)
C_POINTER($3;$ptrArr)
C_LONGINT($pos;$vlElem)
$string:=$1
$Separator:=$2
$ptrArr:=$3
$pos:=Position($Separator;$string)
While (Length($string)>0)
If ($pos#0)
If ($pos#1)
$vlElem:=Size of array($ptrArr->)+1
INSERT ELEMENT($ptrArr->;$vlElem)
$ptrArr->{$vlElem}:=Substring($string;1;$pos-1)
$string:=Delete string($string;1;$pos)
Else
$string:=Delete string($string;1;1)
End if
$pos:=Position($Separator;$string)
Else
$vlElem:=Size of array($ptrArr->)+1
INSERT ELEMENT($ptrArr->;$vlElem)
$ptrArr->{$vlElem}:=$string
$string:=""
End if
End while

The following is a sample call to this method:

$string:="Hello;Goodbye;Monday;Computer"
$Separator:=";"
ARRAY TEXT(vTextArray;0)
GetStringToken ($string;$seperator;->vTextArray)

Result:
vTextArray{1} is Hello
vTextArray{2} is Goodbye
vTextArray{3} is Monday
vTextArray{4} is Computer