String Operations
Start with String Operations
The strings package provides standard operations for searching, replacing, trimming and splitting text. Using it is usually clearer than writing manual byte loops.
What you’ll learn
- Explain the main purpose of string operations.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Import strings to use functions such as Contains, HasPrefix, TrimSpace, ToUpper and ReplaceAll. These functions return values; they do not mutate the source string.
Choose operations according to meaning. For example, strings.TrimSpace removes leading and trailing Unicode whitespace, while strings.ReplaceAll replaces matching substrings throughout the text. Case conversions are Unicode-aware but are not a universal locale-sensitive comparison strategy.
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() {
raw := " learn go today "
clean := strings.TrimSpace(raw)
fmt.Println("Clean:", clean)
fmt.Println("Contains go:", strings.Contains(clean, "go"))
fmt.Println("Upper:", strings.ToUpper(clean))
fmt.Println("Replace:", strings.ReplaceAll(clean, "go", "Go"))
}
Output
Clean: learn go today
Contains go: true
Upper: LEARN GO TODAY
Replace: learn Go todayTrace what the program does
TrimSpace produces a new string without outer spaces. Contains finds the lowercase substring go and returns true. ToUpper produces uppercase text, while ReplaceAll changes only the matching go substring in its returned result. The raw string remains unchanged.
Avoid common mistakes
strings.Containsis case-sensitive.- Standard string functions return new strings; they do not edit the input in place.
Try it yourself
Use strings.HasPrefix to check whether the cleaned text begins with learn, then replace today with now.
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 String Operations 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.