examples/gallery/07-strings.hero
Come leggere i byte di una stringa e come scorrerne i caratteri.
- 66 righe
Una stringa str usa UTF-8, un formato in cui un carattere può occupare più byte, e non può essere modificata. La sua lunghezza si misura in byte: s[i] restituisce il valore numerico di un byte, mentre s.chars() scorre i caratteri. Le due operazioni hanno nomi diversi perché restituiscono risultati diversi.
Eseguilo
Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.
Il programma
## Strings
#
# A `str` is immutable UTF-8, indexed in bytes. `s[i]` is an `i64` in
# 0..255, and `s.chars()` walks characters as one-character strings — the
# two are different jobs and the language refuses to blur them.
# Bytes, not characters: this counts the ASCII spaces.
function space_count(s: str) -> i64
seen: i64 @= 0
for i in range(from: 0, to: s.len())
if s[i] == ' '
seen @ seen + 1
return seen
# Characters, not bytes: this one is right for text.
function letters_of(s: str) -> [str]
out: [str] @= []
for c in s.chars()
if c != " "
out @ out.push(c)
return out
# Splitting on a single space, written out. There is no library to hide in.
function words_of(s: str) -> [str]
out: [str] @= []
start: i64 @= 0
for i in range(from: 0, to: s.len())
if s[i] == ' '
if i > start
out @ out.push(s.slice(from: start, to: i))
start @ i + 1
if s.len() > start
out @ out.push(s.slice(from: start, to: s.len()))
return out
# `join` is the other direction, and the separator is an argument, not a
# convention.
function sentence_of(words: [str]) -> str
return words.join(" ")
function initials_of(words: [str]) -> str
out: str @= ""
for w in words
if w.len() > 0
out @ out + w.slice(from: 0, to: 1)
return out
test "bytes, characters and words"
assert space_count("a b c") == 2
assert letters_of("a b").len() == 2
assert words_of("one two three").len() == 3
assert sentence_of(["one", "two"]) == "one two"
assert initials_of(["heroes", "language"]) == "hl"
function main()
words = words_of("the quick brown fox")
print(sentence_of(words))
print(initials_of(words))
impronta sha256 468f3ee13579 · 1 file · index.json
Successivo: 08-ffi. Tutti gli esempi. ← Precedente: 06-generics
Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.