Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Split and Join

A line of comma-separated values, a path, a list of words: text that is really a list of fields. strings.Split turns it into a list you can walk, and strings.Join turns a list back into text.

#import "std/strings"

'' Split cuts a string at every delimiter and returns the pieces
'' in an Array( of ustring ).
var fields = strings.Split( "red,green,,blue", "," )
print "fields:"; fields.Count( )
for each f in fields
    print "  ["; f; "]"
next

'' Indexing counts from 0, like every container.
print "first is "; fields[ 0 ]; ", last is "; fields[ fields.Count( ) - 1 ]

'' Join is the reverse: pieces in, one string out.
print strings.Join( fields, " + " )

'' Splitting and joining with the same delimiter gives back the
'' original, empty fields and all.
dim as ustring row = ",a,,b,"
print cbool( strings.Join( strings.Split( row, "," ), "," ) = row ); _
      " (" & strings.Split( row, "," ).Count( ) & " fields)"

'' SplitChars treats every character it is given as a delimiter.
var words = strings.SplitChars( "one two;three,four", " ;," )
print strings.Join( words, "|" )

Output

fields: 4
  [red]
  [green]
  []
  [blue]
first is red, last is blue
red + green +  + blue
true (5 fields)
one|two|three|four

Split returns an Array( of ustring ), the standard library's growable array from Containers. Here it is asked only for .Count( ), for an element with [ i ], and to be walked with for each. Its indexes count from 0, unlike positions inside a string, which count from 1.

Split never drops a field. Two delimiters in a row make an empty field between them, and a delimiter at either end makes an empty field there, so ",a,,b," is five fields and n delimiters always give n + 1 fields. That rule is what makes the round trip work: Join( Split( s, d ), d ) is s again, for every s.

When the delimiter is a choice of characters rather than one string, SplitChars takes them all at once: " ;," splits at a space, a semicolon or a comma.

Note

A comma-separated file is not a Split problem: a quoted field such as "London, UK" contains the delimiter. strings.SplitCsvRow and strings.SplitCsv read quoting correctly, and Writing CSV shows the other direction.

Activities

  1. Split "1969-07-20" on "-" and print the three parts as numbers with val.
  2. Split a sentence into words with SplitChars, then Join them back in reverse order.