Splitting a Text String into Array Elements
- Last UpdatedOct 24, 2022
- 2 minute read
You can split a text string into its component fields and store each field in a separate array element using the Split() method of a text string. This can be useful after reading a record from a file into a variable. By default, the delimiter is any white-space character (tab, space, or newline):
!Line = '123 456 789'
!ArrayOfFields = !Line.split()
The white-space is treated as a special case since consecutive white-spaces are treated as a single delimiter and white-spaces at the start or finish of the string are ignored.
The result is to create the array-variable !ArrayOfFields (if it does not already exist) with the element !FIELDS[1] set to '123', !FIELDS[2] set to '456', and !FIELDS[3] set to '789'.
To specify a different delimiter, specify the required (single) character as the argument to the Split() method:
!Line = '123 ,456 ,,789'
!ArrayOfFields = !Line.split(',')
In this example, comma is used as the delimiter. !ArrayOfFields is created if it does not already exist with the element !FIELDS[1] set to '123', !FIELDS[2] set to '456', !FIELDS[3] created but set to zero length, and !FIELDS[4] set to '789'.
Note:
In this case, unlike the white-space delimiter, consecutive occurrences of the comma
define empty elements.
Note:
The only way to set the special white-space delimiter is by default; that is, by not
specifying any delimiter as an argument to the Split() method. If a space is specified explicitly as the delimiter (as ' '), it will behave in the same way as comma in this example.
You can combine an array-append method with a text-string Split() method in a single command to append the fields of a text string to the end of an existing array variable, thus:
!ArrayOfFields.AppendArray(!Line.Split())