Skip to content

String

A UTF-8 encoded string.

Strings are immutable. Indexing and slicing one means picking a unit: byte_at() and bytes() count bytes, while rune_at() and substring() count runes. length() counts bytes, so it does not agree with substring() on text outside ASCII.

See Lexemes for string literals

Returns the number of bytes in the string. To count runes, use runes().length().

impl string {
fn length(self) -> int
}
let bytes = "café".length()5, since é is two bytes

Returns true if the string has length zero.

impl string {
fn is_empty(self) -> bool
}
let blank = "".is_empty()true

Returns true if the string contains the given substring.

impl string {
fn contains(self, substr: string) -> bool
}
let found = "hello world".contains("world")true

Splits the string around each occurrence of sep and returns the substrings.

impl string {
fn split(self, sep: string) -> mut Slice<string>
}
let fields = "alice,30,berlin".split(",")["alice", "30", "berlin"]

Returns true if the string starts with prefix.

impl string {
fn starts_with(self, prefix: string) -> bool
}
let is_go = "go:fmt".starts_with("go:")true

Returns true if the string ends with suffix.

impl string {
fn ends_with(self, suffix: string) -> bool
}
let is_lisette = "main.lis".ends_with(".lis")true

Returns the byte at byte index i.

impl string {
fn byte_at(self, i: int) -> byte
}
let first = "hello".byte_at(0)104, the byte value of h

Returns the rune at rune index i. The index counts runes, not bytes, so the last valid index is runes().length() - 1, not length() - 1.

impl string {
fn rune_at(self, i: int) -> rune
}
let accented = "café".rune_at(3)233, the code point of é

Returns the bytes of the string as a Slice<byte>.

impl string {
fn bytes(self) -> mut Slice<byte>
}
let raw = "hi".bytes()[104, 105], one byte per char

Returns the runes of the string as a Slice<rune>.

impl string {
fn runes(self) -> mut Slice<rune>
}
let points = "café".runes()[99, 97, 102, 233], one code point per char
let count = points.length()4, one fewer than length()

Returns the substring at the given rune-indexed range.

impl string {
fn substring(self, r: Range<int>) -> string
}
let word = "hello world".substring(0..5)"hello"