String Manipulation
Go string formatting, conversion, and regular expressions.
String Formatting
name := "Ada"
age := 30
fmt.Sprintf("%s is %d", name, age) // "Ada is 30"
fmt.Sprintf("%+v", person) // struct with field names
fmt.Sprintf("%#v", person) // Go syntax representation
Common verbs: %s (string), %d (int), %f (float), %v (default), %+v (struct fields), %T (type).
String Methods
The strings package provides:
import "strings"
strings.TrimSpace(" hi ") // "hi"
strings.ToUpper("hello") // "HELLO"
strings.ToLower("HELLO") // "hello"
strings.Replace("foo", "o", "0", -1) // "f00"
strings.Split("a,b,c", ",") // ["a", "b", "c"]
strings.Join([]string{"a","b"}, "-") // "a-b"
strings.HasPrefix("hello", "he") // true
strings.Contains("hello", "ell") // true
Conversions (strconv)
import "strconv"
strconv.Itoa(42) // "42"
strconv.Atoi("42") // 42, nil
strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14"
Regex
import "regexp"
re := regexp.MustCompile(`\d+`)
re.FindString("abc123") // "123"
re.FindAllString("a1b2c3", -1) // ["1", "2", "3"]
re.ReplaceAllString("a1b2c3", "#") // "a#b#c#"
Next: Structs & Interfaces