Strings

String literals, interpolation, methods, and the string builder in Chasm.

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.

MethodFree functionReturnsDescription
s.lenstr_len(s)intByte length
s[i]str_char_at(s, i)intByte at index
s.slice(from, to)str_slice(s, from, to)stringSubstring [from, to)
s.concat(t)str_concat(s, t)stringConcatenate
s.repeat(n)str_repeat(s, n)stringRepeat n times
s.upper()str_upper(s)stringUppercase copy
s.lower()str_lower(s)stringLowercase copy
s.trim()str_trim(s)stringStrip leading/trailing whitespace
s.contains(sub)str_contains(s, sub)boolSubstring check
s.starts_with(p)str_starts_with(s, p)boolPrefix check
s.ends_with(p)str_ends_with(s, p)boolSuffix check
s.eq(t)str_eq(s, t)boolEquality 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 thing

String 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
FunctionDescription
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.