Longitud e Iteración de Caracteres
En esta página
.len() devuelve el número de bytes de la string, no el número de caracteres
Unicode. Para texto ASCII puro los valores coinciden; los caracteres acentuados o
los emoji pueden ocupar más de un byte.
.chars() devuelve un array de strings — cada elemento es un carácter (una
string de longitud 1). Itera con for para procesar letra a letra:
.len() para medir; .chars() para iterar y contar ocurrencias.
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
Desafío
Escribe una función invertir(s: str) -> str que recorra .chars() de atrás
hacia adelante (usa un índice decreciente) y acumule los caracteres con +.
Pruébala con "zolo" — el resultado debe ser "oloz".
Consulta también