The strings Package
Start with The strings Package
The strings package transforms and inspects UTF-8 text without changing immutable Go string values in place.
What you’ll learn
- Explain the main purpose of the strings package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use strings.Contains for substring checks, strings.TrimSpace to remove surrounding whitespace, strings.Split to divide text, and strings.Join to assemble pieces. These functions return new values or information; they do not mutate an existing string.
Some operations work on Unicode code points while others act on bytes or exact sequences. For human-language case conversion, simple uppercasing is not the same as locale-specific text processing.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strings"
)
func main() {
title := strings.TrimSpace(" Go,Java,Python ")
langs := strings.Split(title, ",")
fmt.Println("Count:", len(langs))
fmt.Println("Joined:", strings.Join(langs, " | "))
fmt.Println("Has Go:", strings.Contains(title, "Go"))
}
Output
Count: 3
Joined: Go | Java | Python
Has Go: trueTrace what the program does
TrimSpace removes external spaces, Split makes three elements, Join recombines them with separators, and Contains locates the exact substring Go.
Avoid common mistakes
- strings.Contains is case-sensitive.
- Do not confuse len(string) in bytes with the number of human-perceived characters.
Try it yourself
Split a comma-separated list of three cities and join them using a slash.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced The strings Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.