Strings in Chasm are immutable UTF-8 byte sequences. All string operations produce new strings, the original is never modified.
Literals and Interpolation
greeting = "Hello, world!"
name = "Chasm"
score = 42
msg = "#{name} score: #{score}" # "Chasm score: 42"Any expression is valid inside #{}:
status = "HP: #{to_int(@hp * 100)}% | Frame #{@frame}"Length and Indexing
s = "hello"
n = s.len # 5, or: str_len(s)
b = s[0] # 104 (byte value of 'h'), or: str_char_at(s, 0)Indexing returns the raw byte value as an int, not a character. Use str_from_char to convert back:
ch = str_from_char(s[0]) # "h"Common Methods
All methods have an equivalent free function form, use whichever reads better.
| Method | Free function | Returns | Description |
|---|---|---|---|
s.len | str_len(s) | int | Byte length |
s[i] | str_char_at(s, i) | int | Byte at index |
s.slice(from, to) | str_slice(s, from, to) | string | Substring [from, to) |
s.concat(t) | str_concat(s, t) | string | Concatenate |
s.repeat(n) | str_repeat(s, n) | string | Repeat n times |
s.upper() | str_upper(s) | string | Uppercase copy |
s.lower() | str_lower(s) | string | Lowercase copy |
s.trim() | str_trim(s) | string | Strip leading/trailing whitespace |
s.contains(sub) | str_contains(s, sub) | bool | Substring check |
s.starts_with(p) | str_starts_with(s, p) | bool | Prefix check |
s.ends_with(p) | str_ends_with(s, p) | bool | Suffix check |
s.eq(t) | str_eq(s, t) | bool | Equality check |
Examples
s = " Hello, Chasm! "
print(s.trim()) # "Hello, Chasm!"
print(s.trim().lower()) # "hello, chasm!"
print(s.contains("Chasm")) # true
print(s.slice(8, 13)) # "Chasm" (after trim)
a = "Hello"
b = ", world"
print(a.concat(b)) # "Hello, world"
print(str_concat(a, b)) # same thingString Builder
When you need to construct a string piece by piece, use the strbuild type. It avoids creating many intermediate strings:
defp join(items :: []string, sep :: string) :: string do
b = str_builder_new()
i = 0
while i < items.len do
if i > 0 do
str_builder_append(b, sep)
end
str_builder_append(b, items.get(i))
i = i + 1
end
return str_builder_build(b)
end| Function | Description |
|---|---|
str_builder_new() | Create a new builder |
str_builder_append(b, s) | Append a string |
str_builder_push(b, byte) | Append a single byte by integer value |
str_builder_build(b) | Finalize and return the accumulated string |
Converting Other Types to String
int_to_str(42) # "42"
float_to_str(3.14) # "3.14"
bool_to_str(true) # "true"
str_from_char(65) # "A"String interpolation calls these implicitly, so "#{42}" and "#{int_to_str(42)}" are equivalent.