Skip to main content

Strings

A Mux string is a sequence of characters, not bytes. Everything that positions a string - its length, an index, a slice, the result of index_of - counts characters, so a string behaves like a list of char and the same operations work on both.

string_positions.mux
Loading...

héllo occupies six bytes and five characters. Reporting six would make accented[4] an error on a string that plainly has five characters in it, so length counts what you can index.

The cost is worth knowing: because characters vary in width, length walks the string rather than reading a stored count. It is O(n), not O(1). Take it once into a variable rather than calling it inside a loop condition.

Indexing

Indexing yields a char, and negative indices count back from the end - the same rule lists follow.

string_indexing.mux
Loading...

Reading past either end is a runtime error. There is a single character at a position or there is not.

Slicing

Slicing takes a range of positions and returns a new string. The bounds are half-open: [0:5] takes positions 0 through 4.

string_slicing.mux
Loading...

Either bound may be omitted and defaults to that end. Out-of-range bounds clamp rather than fail, unlike indexing - a slice asks what is in a range, and an empty answer is a real one.

Taking a string apart

string_methods.mux
Loading...

index_of returns a character offset, not a byte offset, so it can be fed straight back into an index or a slice:

index_of_roundtrip.mux
Loading...

Iterating

A string converts to a list of characters with to_list, and a for loop over a string walks its characters directly.

string_iteration.mux
Loading...

Printing a list<char> shows the code point of each character rather than the character itself, because that is how a char renders inside a collection:

char_list_display.mux
Loading...

Those are the code points of h é l l o. Print the string itself, or a single char with .to_string(), when you want the characters.

Building strings

+ concatenates, and every type with a to_string can join a string that way.

string_building.mux
Loading...

There is no implicit conversion: name + age does not compile. The to_string call is the conversion, written where it happens.

See Also

  • Types - char, and converting between types
  • Collections - lists, and the slicing rules strings share with them