String.cut
func String.cut(s: string, sep: string): String.Cut | nullString.cut splits s around the first occurrence of sep, or returns null when sep does not occur. It panics if sep is empty.
Details
sepis in neither field; any later occurrence ofsepstays inafter.
Basic examples
Split a key from its value at the first =. The rest of the string, later = included, goes to after:
String.cut("k=v=w", "=") // String.Cut{ before: "k", after: "v=w" }When the separator does not occur, the result is null:
String.cut("key", "=") // nullRead one side with ?.:
String.cut("host:8080", ":")?.after // "8080"
String.cut("localhost", ":")?.after // nullScope
A separator at either end leaves an empty side:
"=v".cut("=") // String.Cut{ before: "", after: "v" }
"k=".cut("=") // String.Cut{ before: "k", after: "" }
"=".cut("=") // String.Cut{ before: "", after: "" }The empty string contains no separator:
"".cut("=") // nullA separator can be longer than one character:
"a::b::c".cut("::") // String.Cut{ before: "a", after: "b::c" }
"Content-Type: text/html".cut(": ") // String.Cut{ before: "Content-Type", after: "text/html" }The whole string as the separator leaves both sides empty:
"abc".cut("abc") // String.Cut{ before: "", after: "" }Unicode text and separators work like any other:
"🐜🐝🐞".cut("🐝") // String.Cut{ before: "🐜", after: "🐞" }
"naïve café".cut(" ") // String.Cut{ before: "naïve", after: "café" }The match is exact: case matters, and a precomposed é does not contain the code point e:
"Key=V".cut("k") // null
"é".cut("e") // nullString.cut matches code points, not graphemes, so a separator can split a letter from its combining accent:
"e\u{301}x".cut("\u{301}") // String.Cut{ before: "e", after: "x" }Call it through ., in a pipe, or with named arguments:
"k=v".cut("=") // String.Cut{ before: "k", after: "v" }
"k=v" | String.cut("=") // String.Cut{ before: "k", after: "v" }
String.cut(s: "a-b", sep: "-") // String.Cut{ before: "a", after: "b" }Applications
Parse key=value lines into a map, skipping lines without = with ?? continue:
let text = "name=ant\n# a comment\nversion=0.4\nurl=https://x.org/?a=1\n"
let config: Map[string, string] = Map{}
for line in text.lines() {
let kv = line.cut("=") ?? continue
config[kv.before] = kv.after
}
println(config)Map{ "name": "ant", "version": "0.4", "url": "https://x.org/?a=1" }Narrow the result with != null and fall back when the separator is missing:
func port(address: string): string {
let c = address.cut(":")
if c != null { c.after } else { "80" }
}
println(port("example.org:8080"))
println(port("example.org"))8080
80Return early from a function with ?? return, then destructure the record:
type Email = { user: string, domain: string }
func parseEmail(s: string): Email | null {
let { before, after } = s.cut("@") ?? return null
Email{ user: before, domain: after }
}
println(parseEmail("ann@example.org"))
println(parseEmail("ann"))Email{ user: "ann", domain: "example.org" }
nullCut in a loop to take a string apart one field at a time:
var rest = "a/b/c"
let parts: Array[string] = []
while true {
let c = rest.cut("/")
if c == null {
parts.push(rest)
break
}
parts.push(c.before)
rest = c.after
}
println(parts)["a", "b", "c"]Properties and relations
When the result is not null, joining before, sep, and after gives s back, and before does not contain sep:
let s = "user=ann=admin"
let c = s.cut("=")
assert(c != null)
assert(c.before + "=" + c.after == s)
assert(!c.before.contains("="))The result is null exactly when String.contains is false:
for s in ["k=v", "kv", ""] {
assert((s.cut("=") == null) == !s.contains("="))
}The length of before is the index String.indexOf gives, and before is the first piece String.split gives:
let s = "a,b,c"
let c = s.cut(",")
assert(c != null)
assert(c.before.length() == s.indexOf(","))
assert(c.before == s.split(",")[0])Possible issues
An empty separator panics:
"abc".cut("") // panic: String.cut needs a separator that is not emptyThe result may be null, so reading a field of it without narrowing is a compile error. The same holds for a destructuring:
let c = "a=b".cut("=")
println(c.before) // error: String.Cut | null has no field before: narrow the value firstlet { before, after } = "a=b".cut("=")
// error: String.Cut | null has no field before: narrow the value first
// error: String.Cut | null has no field after: narrow the value first
println(before)Use ?., ??, or a test against null first, as in the examples above.
To treat a missing separator as an empty after, fall back to a String.Cut of your own:
let s = "key"
s.cut("=") ?? String.Cut{ before: s, after: "" } // String.Cut{ before: "key", after: "" }String.cut leaves the white space around the separator in place, so key = value text keeps the spaces on both sides:
"key = value".cut("=") // String.Cut{ before: "key ", after: " value" }Trim each side with String.trim:
("key = value".cut("=")?.after ?? "").trim() // "value"String.cut splits at the first occurrence. To split at the last one, such as the extension of a file name, use String.lastIndexOf and String.slice:
let name = "archive.tar.gz"
name.cut(".")?.after // "tar.gz"
let i = name.lastIndexOf(".")
if i != null { name.slice(i + 1, name.length()) } else { "" } // "gz"See also
String.Cut · String.split · String.indexOf · String.lastIndexOf · String.contains · String.trim · String.trimPrefix · String.lines · ?. operator · ?? operator
