Módulo String
En esta página
Además de la sintaxis de método (s.upper()), el módulo String expone las
mismas operaciones como funciones de módulo (String.upper(s)). Las dos
formas son equivalentes; la elección es cuestión de estilo — el encadenamiento
de métodos tiende a ser más idiomático, mientras que el módulo facilita pasar
funciones como valores.
El módulo también ofrece String.sub (substring por índice 1-based inclusivo)
y String.reverse, que no tienen forma de método nativa:
String.upper, String.sub, String.reverse y verificación de palíndromos.
09-string-module.zolo
// Feature: `String` module — functions as a module
// Syntax: `String.method(s, ...)` (alternative to `s.method(...)`)
// When to use: functional style, passing as a first-class function.
use std::String
// In Zolo, string methods have an equivalent module-function form.
// Useful when you want to compose functions.
// -- upper / lower / len ---------------------------------------
print(String.upper("hello")) // HELLO
print(String.lower("WORLD")) // world
print(String.len("zolo")) // 4
// -- sub: substring by range (1-based, inclusive) -------------
print(String.sub("hello", 1, 3)) // hel
print(String.sub("hello", 2, 4)) // ell
print("hello".sub(1, 3)) // hel (method form)
// -- reverse: reverses ----------------------------------------
print(String.reverse("hello")) // olleh
print(String.reverse("zolo")) // oloz
// Useful for checking palindromes.
fn is_palindrome(s: str) -> bool {
return s == String.reverse(s)
}
print(is_palindrome("racecar")) // true
print(is_palindrome("zolo")) // false
// -- Functional style vs method --------------------------------
// These two do the same thing:
let s = "Hello World"
print(s.upper()) // HELLO WORLD
print(String.upper(s)) // HELLO WORLD
// Chaining method calls is idiomatic:
let clean = " HELLO ".trim().lower()
print(clean)
// expected: hello
Desafío
Usa String.sub para extraer el dominio de "user@example.com" — es decir,
la parte después del @. Pista: localiza el índice del @ con .chars() y
calcula los límites del sub.
Consulta también