Working with Strings

Overview

Strings in Go are immutable sequences of bytes, typically UTF-8 encoded. Understanding the distinction between bytes and runes is essential.

String Basics

s := "Hello, World!"
s := `Raw string with
multiple lines`

Immutability

s := "hello"
// s[0] = 'H'  // Error: cannot assign to s[0]
s = "Hello"    // OK: reassign entire string

Bytes vs Runes

s := "Hello, 世界"

len(s)              // 13 (bytes)
len([]rune(s))      // 9 (characters)

Iterating

// By byte
for i := 0; i < len(s); i++ {
    fmt.Printf("%x ", s[i])
}

// By rune (character)
for i, r := range s {
    fmt.Printf("%d: %c\n", i, r)
}

String Operations

Concatenation

s := "Hello" + ", " + "World"

// Efficient building
var b strings.Builder
b.WriteString("Hello")
b.WriteString(", World")
result := b.String()

Comparison

s1 == s2              // Equality
s1 < s2               // Lexicographic
strings.EqualFold(s1, s2)  // Case-insensitive

strings Package

import "strings"

strings.Contains(s, "sub")      // true/false
strings.HasPrefix(s, "pre")     // true/false
strings.HasSuffix(s, "suf")     // true/false
strings.Index(s, "sub")         // Position or -1
strings.Split(s, ",")           // []string
strings.Join(parts, ",")        // string
strings.ToUpper(s)              // UPPERCASE
strings.ToLower(s)              // lowercase
strings.TrimSpace(s)            // Remove whitespace
strings.Replace(s, "old", "new", n)  // Replace n times
strings.ReplaceAll(s, "old", "new")  // Replace all

strconv Package

import "strconv"

// String to int
n, err := strconv.Atoi("42")

// Int to string
s := strconv.Itoa(42)

// Parse float
f, err := strconv.ParseFloat("3.14", 64)

// Format float
s := strconv.FormatFloat(3.14, 'f', 2, 64)

fmt Package

// Formatting
s := fmt.Sprintf("Name: %s, Age: %d", name, age)

// Parsing
var name string
var age int
fmt.Sscanf("Alice 30", "%s %d", &name, &age)

Rune Operations

r := 'A'
unicode.IsLetter(r)    // true
unicode.IsDigit(r)     // false
unicode.ToUpper(r)     // 'A'
unicode.ToLower(r)     // 'a'

Summary

Operation Method
Length (bytes) len(s)
Length (chars) len([]rune(s))
Concatenate + or strings.Builder
Contains strings.Contains()
Split/Join strings.Split(), strings.Join()
Convert strconv.Atoi(), strconv.Itoa()