Heroes / Examples / 07-strings
examples/gallery/07-strings.hero
Read text as bytes or as whole characters, depending on the task.
- 66 lines
A str stores text as immutable UTF-8: encoded bytes that cannot be changed in place. s[i] returns the numeric value of one byte, while s.chars() visits whole characters. One character can occupy several bytes, so choose the operation your task needs.
Run it
These files introduce the language one feature at a time. This page shows the program and not a result, because no test compares their output byte for byte yet.
The program
## 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))
fingerprint sha256 468f3ee13579 · 1 file · index.json
Next: 08-ffi. All the examples. ← Previous: 06-generics
Run one yourself: the four commands. Learn the language, or read the full specification in one file.