Skip to main content

Mojo struct

GraphemeIndicesIter

struct GraphemeIndicesIter[mut: Bool, //, origin: Origin[mut=mut]]

Iterator over grapheme clusters paired with their starting byte offset.

Each call to __next__() yields a Tuple[Int, StringSlice[origin]] where the first element is the byte offset (relative to the original string) at which the grapheme begins, and the second is the grapheme slice itself.

Mirrors str::grapheme_indices from Rust's unicode-segmentation crate. Useful for text editors and UIs that need to map cursor byte positions back to grapheme boundaries.

Example:

var s = StringSlice("abc")
var pairs = List[Tuple[Int, String]]()
for off, g in s.grapheme_indices():
    pairs.append((off, String(g)))
assert_equal(len(pairs), 3)
assert_equal(pairs[0][0], 0)
assert_equal(pairs[1][0], 1)
assert_equal(pairs[2][0], 2)

Parameters

  • mut (Bool): Whether the slice is mutable.
  • origin (Origin[mut=mut]): The origin of the underlying string data.

Implemented traits

AnyType, Copyable, ImplicitlyCopyable, ImplicitlyDestructible, Iterable, Iterator, Movable

comptime members

Element

comptime Element = Tuple[Int, StringSlice[origin]]

The element type yielded by iteration.

IteratorType

comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]] = GraphemeIndicesIter[origin]

The iterator type for this grapheme indices iterator.

Parameters

Methods

__iter__

__iter__(ref self) -> Self

Iterate over the grapheme indices in the underlying string slice.

Returns:

Self: An iterator yielding (byte_offset, grapheme) pairs.

__next__

__next__(mut self) -> Tuple[Int, StringSlice[origin]]

Get the next (byte_offset, grapheme) pair.

Returns:

Tuple[Int, StringSlice[origin]]: The byte offset at which the next grapheme starts and the grapheme slice itself.

Raises:

StopIteration if the iterator has been exhausted.

Was this page helpful?