Skip to content

String.contains ​

ant
func String.contains(s: string, t: string): bool

String.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, "") is true for any s.

Basic examples ​

ant
String.contains("seafood", "foo") // true
String.contains("seafood", "bar") // false

Call it through . on any string:

ant
let greeting = "hello world"
greeting.contains("o w")   // true
greeting.contains("Hello") // false

Scope ​

With an empty t or an empty s:

ant
"abc".contains("") // true
"".contains("")    // true
"".contains("a")   // false

t may be longer than one code point, and may be all of s:

ant
"ant".contains("ant")  // true
"ant".contains("ants") // false

Non-ASCII text works the same way, by code points:

ant
"naïve café".contains("ï")          // true
"日本語のテキスト".contains("テキ") // true

An emoji joined from several code points contains each of them:

ant
"👨‍👩‍👧".contains("👩") // true

In a pipeline, the string is the first argument:

ant
"key=value" | String.contains("=") // true

Applications ​

Keep the log lines that mention an error:

ant
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:

ant
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"))
text
true
false

Reject a file name that tries to leave its directory:

ant
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"))
text
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:

ant
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:

ant
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:

ant
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
"Ant".contains("ant")                       // false
"Ant".foldCase().contains("ANT".foldCase()) // true

String.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:

ant
let word = "cafe\u{301}"
word.contains("e")                       // true
word.contains("\u{E9}")                  // false
word.normalize("NFC").contains("\u{E9}") // true

A substring is not a word. To test for a whole word, split the text first and use Array.contains:

ant
let text = "the cat sat"
text.contains("he")           // true
text.fields().contains("he")  // false
text.fields().contains("cat") // true

A nullable string, such as the result of Map indexing, is not a string, so it is a compile error:

ant
let user = Map{ name: "Ann" }
println(String.contains(user["name"], "A"))
// error: cannot use string | null where string is expected

Narrow it first:

ant
let user = Map{ name: "Ann" }
let name = user["name"]
if name != null {
  println(name.contains("A"))
}
text
true

Or give a default with ??:

ant
let user = Map{ name: "Ann" }
(user["name"] ?? "").contains("A") // true

String.contains takes a string, not a predicate. To test each character with a function, use String.chars and Array.some:

ant
println(String.contains("abc", { x == "b" }))
// error: a lambda needs an expected function type, but string is expected
ant
"a1b".chars().some({ x.isDigit() }) // true

See also ​

String.startsWith · String.endsWith · String.indexOf · String.lastIndexOf · String.count · String.cut · String.equalFold · String.normalize · String.graphemes · Array.contains