Length and Character Iteration
On this page
.len() returns the number of bytes in the string, not the number of
Unicode characters. For pure ASCII text the values are the same; accented
characters or emoji may occupy more than one byte.
.chars() returns a string array — each element is a character (a string
of length 1). Iterate with for to process letter by letter:
.len() for measuring; .chars() for iterating and counting occurrences.
08-len-and-chars.zolo
// Feature: Length and iteration over characters
// Syntax: `s.len()` -> int, `s.chars()` -> [str]
// When to use: measure length, iterate character by character.
// -- len: byte length ------------------------------------------
print("zolo".len()) // 4
print("".len()) // 0
print("hello world".len()) // 11
// Note: `.len()` returns the length in BYTES, not Unicode code
// points. Accented characters / emoji may take more than one byte.
print("cafe".len()) // 4 (plain ASCII)
print("a".len()) // 1
// -- chars: array of characters (1 string per element) --------
let cs = "abc".chars()
print(cs.len()) // 3
print(cs[0]) // a
print(cs[1]) // b
print(cs[2]) // c
// Iterate character by character.
for c in "zolo".chars() {
print(c)
}
// expected:
// z
// o
// l
// o
// Count occurrences of a character.
fn count_char(s: str, target: str) -> int {
var total = 0
for c in s.chars() {
if c == target {
total = total + 1
}
}
return total
}
print(count_char("mississippi", "s")) // 4
print(count_char("zolo lang", "o")) // 2
// Check whether a string is "empty".
fn is_empty(s: str) -> bool {
return s.len() == 0
}
print(is_empty("")) // true
print(is_empty("x")) // false
Challenge
Write a function reverse(s: str) -> str that walks .chars() backwards
(use a decreasing index) and accumulates the characters with +. Test with
"zolo" — the result should be "oloz".
See also