Page 1 of 1

Split String into Array

Posted: Wed Jun 14, 2017 2:35 am
by jyoung
Is there any way to split a string into an array based on a character?

For example, in most other languages you can do something like String[] myArrary = myString.Split("|").

Does something like this exist in LANSA?

Right now I am using an awful lot of OccurancesOf, PositionOf and Substring to parse a delimited string.

Something like

Code: Select all

define_com class(#PRIM_ACOL<#PRIM_ALPH>) name(#MyArray) reference(*DYNAMIC)
#MyArray <= #UserData.Split( "|" )
Would be great IMHO.

Re: Split String into Array

Posted: Thu Jun 15, 2017 3:10 am
by gstenstrom
This comes from SplitString xDemoUtilities
I copied it to have our own which I use below

Code: Select all

* Utilities - Variety of commonly used methods
Define_Com Class(#OC_RP_DemoUtilities) Name(#Utilities)

Define Field(#w_char) Type(*CHAR) Length(1)
Define Field(#w_token) Reffld(#STD_TEXT)
Define Field(#wlstListCount) Reffld(#ListCount)
Def_List Name(#w_tokenlist) Fields(#w_token) Counter(#wlstListCount) Type(*WORKING) Entrys(*MAX)


* Iterate through the items in the string, using a ~ as the separator and including blank items.
#OC_Ref_EmailAddress := #ADDR10

Clr_List Named(#w_tokenlist)
For Each(#Word) In(#Utilities.SplitString( #addr10 "~" True ))
#w_token := #Word.AsNativeString
Add_Entry To_List(#w_tokenlist)
Endfor
If Cond(#wlstListCount *GT 0)
* use first token for email address
Get_Entry Number(1) From_List(#w_tokenlist) Ret_Status(#IO$STS)
#OC_Ref_EmailAddress := #w_token
Clr_List Named(#w_tokenlist)
Endif

Code: Select all

Mthroutine Name(SplitString)
Define_Map For(*Input) Class(#Prim_dc.UnicodeString) Name(#String)
Define_Map For(*Input) Class(#Prim_dc.UnicodeString) Name(#Separator) Mandatory(" ")
Define_Map For(*Input) Class(#Prim_boln) Name(#IncludeBlankItems) Mandatory(False)
Define_Map For(*Result) Class(#prim_lcol<#Prim_dc.UnicodeString>) Name(#Result) Pass(*by_reference)

Define_Com Class(#prim_nmbr) Name(#Break)

#Result <= *New #prim_lcol<#Prim_dc.UnicodeString>

If (#String <> "")

Begin_Loop

* Look for the first separator in the string
#Break := #String.PositionOf( #Separator )

Case (#Break)

When (= 0) /* No separator found, so must be a whole word remaining */

#Result.Insert( (*New #Prim_dc.unicodeString) )
#Result.Last := #String

Leave

When (= 1) /* Separator is next character, so must be zero length item */

If (#IncludeBlankItems)

#Result.Insert( (*New #Prim_dc.unicodeString) )

Endif

Otherwise /* Substring */

#Result.Insert( (*New #Prim_dc.unicodeString) )
#Result.Last := #String.Substring( 1 (#Break - 1) )

Endcase

* Remove the item from the string
#String := #String.DeleteSubstring( 1 #Break )

End_Loop

Endif

Endroutine