Skip to main content
Log in

Mojo struct

CharsIter

struct CharsIter[mut: Bool, //, origin: Origin[mut]]

Iterator over the Chars in a string slice, constructed by StringSlice.chars().

Parameters

  • mut (Bool): Mutability of the underlying string data.
  • origin (Origin[mut]): Origin of the underlying string data.

Implemented traits

AnyType, Copyable, ExplicitlyCopyable, Movable, UnknownDestructibility

Methods

__next__

__next__(mut self) -> Char

Get the next character in the underlying string slice.

This returns the next Char encoded in the underlying string, and advances the iterator state.

This function will abort if this iterator has been exhausted.

Returns:

The next character in the string.

__has_next__

__has_next__(self) -> Bool

Returns True if there are still elements in this iterator.

Returns:

A boolean indicating if there are still elements in this iterator.

__len__

__len__(self) -> Int

Returns the remaining length of this iterator in Chars.

The value returned from this method indicates the number of subsequent calls to next() that will return a value.

Returns:

Number of codepoints remaining in this iterator.

peek_next

peek_next(self) -> Optional[Char]

Check what the next character in this iterator is, without advancing the iterator state.

Repeated calls to this method will return the same value.

Examples

peek_next() does not advance the iterator, so repeated calls will return the same value:

from collections.string import StringSlice
from testing import assert_equal

var input = StringSlice("123")
var iter = input.chars()

assert_equal(iter.peek_next().value(), Char.ord("1"))
assert_equal(iter.peek_next().value(), Char.ord("1"))
assert_equal(iter.peek_next().value(), Char.ord("1"))

# A call to `next()` return the same value as `peek_next()` had,
# but also advance the iterator.
assert_equal(iter.next().value(), Char.ord("1"))

# Later `peek_next()` calls will return the _new_ next character:
assert_equal(iter.peek_next().value(), Char.ord("2"))
from collections.string import StringSlice
from testing import assert_equal

var input = StringSlice("123")
var iter = input.chars()

assert_equal(iter.peek_next().value(), Char.ord("1"))
assert_equal(iter.peek_next().value(), Char.ord("1"))
assert_equal(iter.peek_next().value(), Char.ord("1"))

# A call to `next()` return the same value as `peek_next()` had,
# but also advance the iterator.
assert_equal(iter.next().value(), Char.ord("1"))

# Later `peek_next()` calls will return the _new_ next character:
assert_equal(iter.peek_next().value(), Char.ord("2"))

.

Returns:

The next character in the underlying string, or None if the string is empty.

next

next(mut self) -> Optional[Char]

Get the next character in the underlying string slice, or None if the iterator is empty.

This returns the next Char encoded in the underlying string, and advances the iterator state.

Returns:

A character if the string is not empty, otherwise None.