String.split
func String.split(s: string, sep: string): Array[string]String.split returns the pieces of s between each occurrence of sep. It panics if sep is empty.
Details
sepmatches code point by code point, as==compares, with no case folding or normalization.- Occurrences of
separe taken from the left and never overlap.
Basic examples
Split a comma-separated list:
String.split("red,green,blue", ",") // ["red", "green", "blue"]Two commas in a row:
String.split("a,b,,c", ",") // ["a", "b", "", "c"]Scope
A string without the separator, and the empty string:
String.split("abc", ",") // ["abc"]
String.split("", ",") // [""]A separator at either end:
String.split(",a,", ",") // ["", "a", ""]
String.split(",", ",") // ["", ""]
String.split("abc", "abc") // ["", ""]A separator can be longer than one character:
String.split("a::b::c", "::") // ["a", "b", "c"]
String.split("a\r\nb", "\r\n") // ["a", "b"]
String.split("one and two", " and ") // ["one", "two"]Unicode text and separators work like any other:
String.split("🐜·🐝·🐞", "·") // ["🐜", "🐝", "🐞"]
String.split("日本,語", ",") // ["日本", "語"]Occurrences are taken from the left without overlap, so "aaa" holds one "aa", not two:
String.split("aaa", "aa") // ["", "a"]
String.split("aaaa", "aa") // ["", "", ""]Here "a" does not match "A", and the combining accent U+0301 on its own is the separator:
String.split("A,b", "a") // ["A,b"]
String.split("e\u{301}x", "\u{301}") // ["e", "x"]Call it through ., in a pipe, or with named arguments:
"a-b".split("-") // ["a", "b"]
"a-b" | String.split("-") // ["a", "b"]
String.split(s: "a-b", sep: "-") // ["a", "b"]Applications
Read a line of comma-separated numbers, with ?? 0 for a field that is not a number:
"3,14,x,15".split(",").map({ x.toInt() ?? 0 }) // [3, 14, 0, 15]Take a path apart and drop the empty pieces that the slashes at the ends leave:
"/usr/local/bin/".split("/").filter({ !x.isEmpty() }) // ["usr", "local", "bin"]Parse rows of a simple table into records, checking the number of columns:
type Person = { name: string, age: int }
func parse(row: string): Person | null {
let cols = row.split(";")
if len(cols) != 2 {
return null
}
let age = cols[1].trim().toInt() ?? return null
Person{ name: cols[0].trim(), age }
}
for row in ["Ann; 31", "Bob;27", "broken", "Eve;x"] {
println(parse(row))
}Person{ name: "Ann", age: 31 }
Person{ name: "Bob", age: 27 }
null
nullCount how often each tag occurs in a comma-separated list:
let counts: Map[string, int] = Map{}
for tag in "ant,bee,ant,ant,bee".split(",") {
counts[tag] = (counts[tag] ?? 0) + 1
}
println(counts)Map{ "ant": 3, "bee": 2 }Properties and relations
For this s, joining the pieces with "," gives s back, and no piece contains ",":
let s = ",a,,b,"
let pieces = s.split(",")
assert(String.join(pieces, ",") == s)
assert(pieces.every({ !x.contains(",") }))For each of these strings, there is one piece more than there are commas:
for s in ["", "a", "a,b", ",,"] {
assert(len(s.split(",")) == s.count(",") + 1)
}The first piece is the before of String.cut, when the separator occurs:
let s = "k=v=w"
let c = s.cut("=")
assert(c != null)
assert(s.split("=")[0] == c.before)Possible issues
An empty separator panics. Use String.chars to take a string apart into code points:
String.split("abc", "") // panic: String.split needs a separator that is not empty
String.chars("abc") // ["a", "b", "c"]The pieces keep any space next to the separator. Trim each piece, or split at ", " when the input always has the space:
String.split("a, b, c", ",") // ["a", " b", " c"]
String.split("a, b, c", ",").map({ x.trim() }) // ["a", "b", "c"]
String.split("a, b, c", ", ") // ["a", "b", "c"]The empty string gives one empty piece, not an empty array:
String.split("", ",") // [""]
len(String.split("", ",")) // 1Here the line break at the end, as a file has it, gives an empty last piece. String.lines drops it, and drops a \r before each \n too:
String.split("a\r\nb\n", "\n") // ["a\r", "b", ""]
String.lines("a\r\nb\n") // ["a", "b"]Splitting at one space leaves an empty piece at each end and between the two spaces. String.fields splits at runs of any white space:
String.split(" a b ", " ") // ["", "a", "", "b", ""]
String.fields(" a b ") // ["a", "b"]To split only at the first separator, as in key=value text where the value can hold the separator, use String.cut:
String.split("k=v=w", "=") // ["k", "v", "w"]
String.cut("k=v=w", "=") // String.Cut{ before: "k", after: "v=w" }Splitting CSV at "," breaks a quoted field that holds a comma. Use Csv.parse for real CSV:
String.split("a,\"b,c\"", ",") // ["a", "\"b", "c\""]
Csv.parse("a,\"b,c\"") // Ok{ value: [["a", "b,c"]] }To split at a pattern rather than a fixed string, use Regex.split.
See also
String.join · String.cut · String.fields · String.lines · String.chars · String.count · Regex.split · Csv.parse
