07 / Fundamentals

Strings

Nyx strings are UTF-8 values with a rich set of built-in methods. This example demonstrates the most commonly used operations: trimming whitespace, slicing, case conversion, substring search, splitting, and interpolation.

07-strings.nxSource →
// Strings: length, substring, split, contains, trim, toUpper, interpolación

// bool -> texto: int_to_string() espera un int y un bool no se convierte solo,
// así que la conversión se escribe explícita.
fn si_no(b: bool) -> String {
    if b { return "si" }
    return "no"
}

fn main() -> int {
    let texto: String = "  Hola Nyx  "

    // trim elimina espacios al inicio y al final
    let limpio: String = texto.trim()
    print("trim: '" + limpio + "'")

    // length
    print("longitud: " + int_to_string(limpio.length()))

    // substring(inicio, fin)  — fin es exclusivo
    let sub: String = limpio.substring(0, 4)
    print("substring(0,4): " + sub)

    // toUpper / toLower
    print("toUpper: " + limpio.toUpper())
    print("toLower: " + limpio.toLower())

    // contains
    print("contains 'Nyx': " + si_no(limpio.contains("Nyx")))
    print("contains 'Go': " + si_no(limpio.contains("Go")))

    // split
    let frase: String = "uno dos tres"
    let partes: Array = frase.split(" ")
    print("partes: " + int_to_string(partes.length()))
    for p in partes {
        print("  " + p)
    }

    // interpolación
    let lang: String = "Nyx"
    let v: int = 12
    print("Lenguaje: ${lang} v0.${v}")

    return 0
}
Outputstdout
trim: 'Hola Nyx'
longitud: 8
substring(0,4): Hola
toUpper: HOLA NYX
toLower: hola nyx
contains 'Nyx': si
contains 'Go': no
partes: 3
  uno
  dos
  tres
Lenguaje: Nyx v0.12

How it works

.trim() returns a new string with leading and trailing whitespace removed. The original string is not modified — Nyx strings are immutable values; all methods return new strings.

.substring(start, end) extracts a slice from index start up to but not including index end. Indices are byte positions. .length() returns the byte length of the string, not the number of Unicode code points — for ASCII text they are the same.

.contains(needle) returns a bool, which is why the recipe prints it through the si_no helper instead of int_to_string. .split(separator) splits the string on every occurrence of the separator and returns an Array of the resulting parts.

String interpolation with ${expr} works inside any double-quoted string. The expression can be a variable, a function call, or any other expression — the result is automatically converted to its string representation and embedded inline.