liveBook · Manning

Lastindex

As explained in Julia as a Second Language

lastindex is a Julia function that returns the final valid index of an indexed collection or string.

lastindex returns the final valid index of an indexed collection or string. It is especially useful when walking strings, where character positions may skip because UTF-8 characters use different numbers of code units. section 11.1.1

Walk an indexed value safely

For an array, indices increase normally: i = firstindex(xs); while i <= lastindex(xs); println((i, xs[i])); i = nextind(xs, i); end. The same pattern works for strings, but nextind advances over complete characters rather than blindly incrementing. For ordinary iteration, prefer for loops; use eachindex when you need character indices. section 11.1.1

How Julia as a Second Language covers it

How deep it goes
Explains final-index lookup through Unicode-aware loops, while deferring routine use to for and eachindex.
Examples
Demonstrates array and Unicode-string while loops, including the nonconsecutive indices of Þrúðvangar.
What it assumes
Assumes basic Julia indexing and loops while clarifying why strings cannot use character counts as direct indices.
What you can do after
Apply it via Julia indexing functions to write bounds-aware traversal for arrays and strings.
How it connects
Connects indexed collections with firstindex, nextind, eachindex, strings, arrays, Unicode, and UTF-8.

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.