Aiming for Jarvis, Creating D.A.N.I.

Tutorial 11: Strings and text (or, How to handle the messiest data type in existence)

If there's one thing I’ve learned in thirty years of writing software, it's that strings are where code goes to die. They look simple—just a sequence of characters—but they are the source of more memory leaks, encoding headaches, and "wait, why is that null?" moments than anything else in the stack.

In Skink, we try to make them behave, but remember: treat them with respect.

The basics: Length and equality

Need to know how long a string is? Don't guess. Use std/str. It saves you from off-by-one errors that are so common they should have their own monument.

import "std/str"

fn main() -> int {
    s := "The server is hungry"
    print("Length: {str.Len(s)}")
    
    if str.Equal(s, "The server is hungry") {
        print("We are talking about the same thing.")
    }
    return 0
}

Searching: Finding the needle

Whether you're parsing a log file or checking if a background process is trying to tell you something vaguely threatening, searching is a daily chore.

if str.Contains("The server is eating the config files again", "config") {
    print("Yup, we have a problem.")
}

// Need the exact spot? 
idx := str.IndexOf("The server is eating the config files again", "again")
print("Trouble detected at index: {idx}")

Slicing, Dicing, and Case

Sometimes you need just a piece of the story, or you need to scream at the console in UPPERCASE.

// Slicing: Be careful with the bounds, or you'll trigger a panic
sub := str.Substr("The server is eating", 0, 10)

upper := str.ToUpper(sub)
print(upper) // "THE SERVER"

Splitting and Joining: The data shuffle

If your data comes in as a CSV—or, heaven forbid, some ancient proprietary format—Split and Join are your best friends.

parts := str.Split("CPU,Memory,Disk", ",")
joined := str.Join(parts, " | ")
print(joined) // "CPU | Memory | Disk"

The Builder: Don't murder your memory

This is the most important part of this tutorial. If you find yourself doing s = s + "more text" inside a loop, stop. You are creating a new string in memory every single iteration, and the Garbage Collector will eventually come for you. Use a Builder.

b := str.NewBuilder(64)
b.Write("System")
b.Write(" is ")
b.Write("online")
print(b.String())

Exercises

  1. Word Counter: Write a program that counts the number of words in a sentence by splitting on spaces and printing the array length.
  2. The Reformatter: Take a comma-separated list of items and turn them into a colon-separated one. It’s cleaner, I promise.
  3. The Sanitizer: Use str.Trim to strip the whitespace from a user's input—you never know what kind of messy data people are going to paste into your prompts.

Next

When you're ready to start serializing your data so it can travel across the network, we'll talk about JSON.