Page 1 of 1

Turning string into array?

Posted: Sun Mar 15, 2015 3:51 pm
by trevordevore
In LCB the split command works on lists. I'm looking for a handler that will convert a string into an array. For example, convert a URL query string of key/value pairs into an array.

Does such a handler exist yet or should I just execute LCS for the time being?

Re: Turning string into array?

Posted: Sun Mar 15, 2015 4:09 pm
by LCMark
@trevordevore: There isn't an equivalent of 'split <String> by <x> and <y>' yet. You could use somthing along these lines though directly in LCB:

Code: Select all

handler SplitStringIntoArray(in pString as String, in pKeyDel as String, in pValueDel as string) as Array
    variable tResult as Array
    put the empty array into tResult

    variable tKeyValue as String
    split pString by pKeyDel
    repeat for each element tKeyValue in the result
        split tKeyValue by pValueDel
        put element 2 of the result into tArray[element 1 of the result]
    end repeat

    return tResult
end handler

Re: Turning string into array?

Posted: Sun Mar 15, 2015 4:28 pm
by trevordevore
Thanks Mark. I just changed tArray to tResult in the repeat loop (and made some syntax changes as I'm using develop) and got it working (see below). Looking at the function I noticed that you are using 'the result' as the target of the repeat loop and then 'the result' within the repeat loop as well. It would appear that the value of the target object of a repeat loop is captured when the repeat loop begins and that modifying it during the repeat loop doesn't affect the repeat loop. Is that correct?

Code: Select all

handler SplitStringIntoArray(in pString as String, in pKeyDel as String, in pValueDel as String) returns Array
	variable tResult as Array
	put the empty array into tResult

	variable tKeyValue as String
	split pString by pKeyDel
		
	repeat for each element tKeyValue in the result
		split tKeyValue by pValueDel
		put element 2 of the result into tResult[element 1 of the result]
	end repeat

	return tResult
end handler

Re: Turning string into array?

Posted: Sun Mar 15, 2015 4:35 pm
by LCMark
Yes, the container in a repeat for each is an input argument and so 'copies' the value.

'the result' is a read-only expression and is always the return value of the previously executed command (control structures are ignored) (handlers returning nothing set the result to 'undefined').

Re: Turning string into array?

Posted: Mon Mar 16, 2015 8:51 am
by n.allan
In the above LCB script, You defined and initialised the variable tResult as Array with "the empty array" but you have not done it for variable tValue as String? Is it only Lists and Array variables that need to be initialised?

Re: Turning string into array?

Posted: Mon Mar 16, 2015 9:14 am
by LCMark
@n.allan: The 'tKeyValue' gets initialized by the repeat for each statement. On each iteration of the loop, repeat for each puts the next element into the iterand variable.