← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 1 of 10

The strings Package

The strings package is a toolbox full of little helpers for slicing, searching, and reshaping text.

Searching Within Strings

strings.Contains, HasPrefix, and HasSuffix check whether a string contains, starts with, or ends with a given substring, returning a simple boolean without needing manual index math.

Example: Searching Within Strings

markup
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Go is fun"
	fmt.Println(strings.Contains(s, "fun"))
	fmt.Println(strings.HasPrefix(s, "Go"))
	fmt.Println(strings.HasSuffix(s, "fun"))
}

Splitting and Joining

strings.Split breaks a string into a slice of substrings around a separator, while strings.Join does the opposite, combining a slice of strings into one, joined by a given separator.

Example: Splitting and Joining

markup
package main

import (
	"fmt"
	"strings"
)

func main() {
	parts := strings.Split("apple,banana,cherry", ",")
	fmt.Println(parts)
	joined := strings.Join(parts, " | ")
	fmt.Println(joined)
}

Case Conversion and Trimming

strings.ToUpper and ToLower normalize case, while strings.TrimSpace removes leading and trailing whitespace -- all common steps before comparing or displaying user-provided text.

Example: Case Conversion and Trimming

markup
package main

import (
	"fmt"
	"strings"
)

func main() {
	raw := "  Hello Go  "
	fmt.Println(strings.ToUpper(strings.TrimSpace(raw)))
}

Replacing Substrings

strings.ReplaceAll swaps every occurrence of a substring for another, while strings.Replace lets you limit how many occurrences are replaced with an explicit count argument.

Example: Replacing Substrings

markup
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "one two two three"
	fmt.Println(strings.ReplaceAll(s, "two", "2"))
}
Common Mistakes
  1. Forgetting strings.Split on a separator not found in the string still returns a one-element slice containing the whole original string.
  2. Using strings.Replace with the wrong count argument (n), not realizing 0 replaces nothing and -1 replaces all occurrences.
  3. Assuming strings.Contains is case-insensitive -- it's a strict substring match; use strings.EqualFold or lowercase both sides for case-insensitive comparisons.
Chapter Summary
  • strings.Contains, strings.HasPrefix, and strings.HasSuffix check for substrings at various positions.
  • strings.Split breaks a string into a slice using a separator; strings.Join does the reverse.
  • strings.ToUpper/ToLower/TrimSpace normalize text for comparison or display.
  • strings.Replace and strings.ReplaceAll substitute occurrences of a substring.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.