String.contains
func String.contains(s: string, t: string): boolString.contains reports whether t occurs in s.
Details
- Matches code point by code point, with no case folding or normalization:
"cafe\u{301}"does not contain"\u{E9}". - The empty string occurs in every string, so
String.contains(s, "")istruefor anys.
Basic examples
String.contains("seafood", "foo") // true
String.contains("seafood", "bar") // falseCall it through . on any string:
let greeting = "hello world"
greeting.contains("o w") // true
greeting.contains("Hello") // falseScope
With an empty t or an empty s:
"abc".contains("") // true
"".contains("") // true
"".contains("a") // falset may be longer than one code point, and may be all of s:
"ant".contains("ant") // true
"ant".contains("ants") // falseNon-ASCII text works the same way, by code points:
"naïve café".contains("ï") // true
"日本語のテキスト".contains("テキ") // trueAn emoji joined from several code points contains each of them:
"👨👩👧".contains("👩") // trueIn a pipeline, the string is the first argument:
"key=value" | String.contains("=") // trueApplications
Keep the log lines that mention an error:
let log = "ok\nERROR: disk full\nok\nERROR: timeout"
log.lines().filter({ x.contains("ERROR") }) // ["ERROR: disk full", "ERROR: timeout"]Search without regard to case by folding both sides with String.foldCase:
func mentions(text: string, word: string): bool {
text.foldCase().contains(word.foldCase())
}
println(mentions("Ant runs on STRASSE 5", "straße"))
println(mentions("Ant runs on Main St", "straße"))true
falseReject a file name that tries to leave its directory:
func safeName(name: string): Result[string, string] {
if name.contains("/") || name.contains("..") {
Result.err("bad name: ${name}")
} else {
Result.ok(name)
}
}
println(safeName("notes.txt"))
println(safeName("../secret"))Ok{ value: "notes.txt" }
Err{ error: "bad name: ../secret" }Properties and relations
For a non-empty t, String.contains agrees with String.indexOf and String.count:
let s = "banana"
for t in ["an", "nab", "a", "x"] {
assert(s.contains(t) == (s.indexOf(t) != null))
assert(s.contains(t) == (s.count(t) > 0))
}A string contains each of its prefixes, suffixes, and slices:
let s = "anthill"
for i in Iter.range(0, s.length() + 1) {
assert(s.contains(s.slice(0, i)))
assert(s.contains(s.slice(i, s.length())))
for j in Iter.range(i, s.length() + 1) {
assert(s.contains(s.slice(i, j)))
}
}String.startsWith and String.endsWith imply String.contains, and String.concat keeps every part:
let a = "ant"
let b = "hill"
let s = String.concat([a, b])
assert(s.startsWith(a) && s.contains(a))
assert(s.endsWith(b) && s.contains(b))Possible issues
The test is case-sensitive. Fold the case of both sides, as in the mentions example above:
"Ant".contains("ant") // false
"Ant".foldCase().contains("ANT".foldCase()) // trueString.contains compares code points, not what a reader sees. An e with a combining accent contains a plain e, and does not contain the single code point \u{E9} until String.normalize composes it:
let word = "cafe\u{301}"
word.contains("e") // true
word.contains("\u{E9}") // false
word.normalize("NFC").contains("\u{E9}") // trueA substring is not a word. To test for a whole word, split the text first and use Array.contains:
let text = "the cat sat"
text.contains("he") // true
text.fields().contains("he") // false
text.fields().contains("cat") // trueA nullable string, such as the result of Map indexing, is not a string, so it is a compile error:
let user = Map{ name: "Ann" }
println(String.contains(user["name"], "A"))
// error: cannot use string | null where string is expectedNarrow it first:
let user = Map{ name: "Ann" }
let name = user["name"]
if name != null {
println(name.contains("A"))
}trueOr give a default with ??:
let user = Map{ name: "Ann" }
(user["name"] ?? "").contains("A") // trueString.contains takes a string, not a predicate. To test each character with a function, use String.chars and Array.some:
println(String.contains("abc", { x == "b" }))
// error: a lambda needs an expected function type, but string is expected"a1b".chars().some({ x.isDigit() }) // trueSee also
String.startsWith · String.endsWith · String.indexOf · String.lastIndexOf · String.count · String.cut · String.equalFold · String.normalize · String.graphemes · Array.contains
