String.lastIndexOf
func String.lastIndexOf(s: string, t: string): int | nullString.lastIndexOf returns the code point index of the last occurrence of t in s, or null when t does not occur.
Details
- The index counts code points, as
String.lengthandString.slicedo. tmatches code point by code point, with no case folding or normalization, soéwritten aseplus a combining accent does not match a precomposedé; normalize both withString.normalizefirst.- The empty string occurs at every index, so an empty
tgives the length ofs.
Basic examples
String.lastIndexOf("banana", "an") // 3
String.lastIndexOf("banana", "x") // nullCall it through . on any string:
"src/lib/main.ant".lastIndexOf("/") // 7
"src/lib/main.ant".indexOf("/") // 3Scope
The last occurrence wins:
String.lastIndexOf("abcabc", "ab") // 3
String.lastIndexOf("a-b-c", "-") // 3The last occurrence may overlap an earlier one, unlike the occurrences String.count counts:
String.lastIndexOf("aaa", "aa") // 1
String.count("aaa", "aa") // 1t may be all of s, but not longer:
String.lastIndexOf("ant", "ant") // 0
String.lastIndexOf("ant", "ants") // nullNothing but "" occurs in "", and "" occurs at the end of every string:
String.lastIndexOf("", "a") // null
String.lastIndexOf("", "") // 0
String.lastIndexOf("café", "") // 4
String.indexOf("café", "") // 0The index counts code points, not bytes. Each of ï and é is one code point and two bytes:
String.lastIndexOf("naïve café, café", "café") // 12
String.lastIndexOf("🐜🐝🐜🐞", "🐜") // 2It counts code points, not what a reader sees as characters. The family emoji is five code points:
String.lastIndexOf("👨👩👧x👨👩👧", "👨👩👧") // 6In a pipe, the string is the first argument:
"a/b/c" | String.lastIndexOf("/") // 3A call can name both arguments:
String.lastIndexOf(s: "a.b.c", t: ".") // 3Applications
Take the extension of a file name, the text after the last dot, and return early with ?? return when there is none:
func extension(name: string): string {
let i = name.lastIndexOf(".") ?? return ""
name.slice(i + 1, name.length())
}
println(extension("archive.tar.gz"))
println(extension("README"))gzSplit a path into its directory and its base name at the last slash:
type Split = { dir: string, base: string }
func splitPath(path: string): Split {
let i = path.lastIndexOf("/")
if i == null { return Split{ dir: "", base: path } }
Split{ dir: path.slice(0, i), base: path.slice(i + 1, path.length()) }
}
println(splitPath("docs/lib/String/lastIndexOf.md"))
println(splitPath("README.md"))Split{ dir: "docs/lib/String", base: "lastIndexOf.md" }
Split{ dir: "", base: "README.md" }Find every occurrence from the end, searching again in the text in front of each match, and stop with ?? break:
let s = "the cat and the hat"
var to = s.length()
let hits: Array[int] = []
while true {
let i = s.slice(0, to).lastIndexOf("the") ?? break
hits.push(i)
to = i
}
println(hits)[12, 0]Properties and relations
The result is null exactly when String.contains is false, and it is never before the index String.indexOf gives:
let s = "banana"
for t in ["an", "nab", "a", "x"] {
let first = s.indexOf(t)
let last = s.lastIndexOf(t)
assert((last == null) == !s.contains(t))
if first != null && last != null {
assert(first <= last)
}
}When t occurs, the slice of s at the index is t:
let s = "mississippi"
let t = "ssi"
let i = s.lastIndexOf(t)
assert(i != null)
assert(s.slice(i, i + t.length()) == t)For a one-code-point t, the index is the one Array.lastIndexOf gives on String.chars:
let s = "hello"
for c in ["h", "l", "o", "z"] {
assert(String.lastIndexOf(s, c) == Array.lastIndexOf(s.chars(), c))
}Possible issues
A missing match is null, not -1, so a test written as in JavaScript is a compile error:
if String.lastIndexOf("abc", "z") >= 0 {
// error: >= needs both operands of one type, got int | null and int
println("found")
}Compare against null instead, or use String.contains when the index does not matter:
String.lastIndexOf("abc", "z") != null // false
String.contains("abc", "z") // falseThe result is not an int until you narrow it, so arithmetic on it is a compile error:
let i = String.lastIndexOf("a.b", ".")
println(i + 1) // error: + needs both operands of one type, got int | null and intGive a default with ?? when one makes sense:
(String.lastIndexOf("a.b", ".") ?? -1) + 1 // 2The index counts code points, so it differs from a byte offset once non-ASCII text comes before the match:
String.lastIndexOf("café!", "!") // 4
"café".toBytes().length() // 5The search is case-sensitive, and a precomposed é does not contain the code point e:
String.lastIndexOf("Ant ant", "Ant") // 0
String.lastIndexOf("Ant ant".toLower(), "ant") // 4
String.lastIndexOf("café", "e") // nullThe index counts code points of the lowered copy, which can be longer than s, since String.toLower uses the full case mappings:
String.lastIndexOf("İx", "x") // 1
String.lastIndexOf("İx".toLower(), "x") // 2See also
String.indexOf · String.contains · String.endsWith · String.count · String.slice · String.chars · Array.lastIndexOf · Bytes.indexOf · ?? operator
