Quirrel4.41.0

string.split_by_chars

Defined in module "string"
from "string" import split_by_chars
split_by_chars(str: string, separators: string, [skip_empty: bool]): array

Splits str into an array of strings at every character that occurs in separators.

examples/string/split_by_chars-basic.nut
from "string" import split_by_chars

let squadIds = split_by_chars("102-7/13", "-/")  // separators is a SET of characters

println("squadIds[0] =", squadIds[0])
println("squadIds[2] =", squadIds[2])
Output:
squadIds[0] = 102
squadIds[2] = 13

Parameters

strstringthe string to split
separatorsstringthe set of characters that split str, each one its own separator; not a substring to match as a whole
skip_emptyboolwhen true, a piece with zero characters is left out of the result instead of being added as "" optional

Return value

An array of the pieces of str, in the order they occur, with every separator character removed.

Errors

Throws empty separators string when separators is "".

Notes

separators is a set, not a literal string: split_by_chars("1-2/3", "-/") splits on - and on / separately, not on the two-character run -/.

A leading separator makes an empty first piece, unless skip_empty is true. A trailing separator never makes an empty last piece, with skip_empty true or false: the scan only emits a final piece when something follows the last separator, so nothing is left to emit. Two separators in a row make an empty piece between them, again unless skip_empty is true.

Example

examples/string/split_by_chars.nut
from "string" import split_by_chars

function show(a) {
  let out = []
  foreach (s in a) out.append($"[{s}]")
  println(",".join(out))
}

// separators is a SET of characters, not a substring: any of ".-/;" splits
println("split_by_chars(\"1.2-3;;4/5\", \".-/;\") =")
show(split_by_chars("1.2-3;;4/5", ".-/;"))
println("split_by_chars(\"1.2-3;;4/5\", \".-/;\", true) =") // skip_empty drops the "" from ";;"
show(split_by_chars("1.2-3;;4/5", ".-/;", true))

// a leading separator makes an empty first piece; a trailing one makes none,
// with skip_empty or without it
println("split_by_chars(\",a,\", \",\") =")
show(split_by_chars(",a,", ","))
Output:
split_by_chars("1.2-3;;4/5", ".-/;") =
[1],[2],[3],[],[4],[5]
split_by_chars("1.2-3;;4/5", ".-/;", true) =
[1],[2],[3],[4],[5]
split_by_chars(",a,", ",") =
[],[a]

See also

stripReturns str with white-space characters removed from both ends.
joinJoins the items of arr into one string, with str between each pair.
stringmodule index