Pular para o conteúdo

Módulo String

Nesta página

Além da sintaxe de método (s.upper()), o módulo String expõe as mesmas operações como funções de módulo (String.upper(s)). As duas formas são equivalentes; a escolha é questão de estilo — encadeamento de métodos tende a ser mais idiomático, enquanto o módulo facilita passar funções como valores.

O módulo também oferece String.sub (substring por índice 1-based inclusivo) e String.reverse, que não têm forma de método nativa:

String.upper, String.sub, String.reverse e verificação de palíndromo.

09-string-module.zolo
Playground
// 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

Desafio

Use String.sub para extrair o domínio de "user@example.com" — ou seja, a parte após o @. Dica: localize o índice do @ com .chars() e calcule os limites do sub.

Buscar no Zolo

9 resultados

enespt-br