Nyx by Example

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.

Code

// Strings: length, substring, split, contains, trim, toUpper, interpolación

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': " + int_to_string(limpio.contains("Nyx")))
    print("contains 'Go': " + int_to_string(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
}

Output

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

Explanation

.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 1 if the substring is found, 0 otherwise. .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.

← Previous Next →

Source: examples/by-example/07-strings.nx