String Programs
Start with String Programs
Learn string programs through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of string programs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Go strings contain bytes and are typically UTF-8 encoded. Many beginner string exercises must distinguish byte indexes, Unicode code points, and user-perceived characters.
The example reverses runes, not raw bytes. It preserves multi-byte code points, though grapheme clusters can still contain more than one rune.
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"
func reverseRunes(s string) string {
chars := []rune(s)
for left, right := 0, len(chars)-1; left < right; left, right = left+1, right-1 {
chars[left], chars[right] = chars[right], chars[left]
}
return string(chars)
}
func main() { fmt.Println(reverseRunes("Go世界")) }
Output
界世oGTrace what the program does
The string becomes a rune slice containing G, o, 世 and 界. Reversing rune order yields 界世oG without corrupting UTF-8 bytes.
Avoid common mistakes
- Reversing runes is not always equivalent to reversing grapheme clusters.
- len(string) counts bytes, not Unicode characters.
Try it yourself
Count runes and bytes for the same input, then try an accent made from combining characters.
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 Programs 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.