Go Tutorial: Strings and strconv
Search, clean, split and join text with the strings package, build strings efficiently, understand bytes vs runes, and convert between text and numbers with strconv.
Working with text
A library runs on text: titles, author names, shelf codes, lists of books typed in by people who press the space bar twice.
Go's `strings` package gives you ready-made tools for searching, cleaning, splitting and joining text, so you rarely have to write those loops yourself. A `strings.Builder` lets you assemble long strings efficiently.
You will also look under the hood. A Go string is a sequence of bytes, and some characters, like the `ë` in Brontë, take more than one. Knowing the difference between bytes and runes saves you from garbled output.
Finally, the `strconv` package converts between numbers and text, and tells you clearly when a piece of text isn't a number at all.
What you'll learn in this Go strings and strconv tutorial
This interactive Go tutorial has 10 hands-on exercises. Estimated time: 25 minutes.
- The strings package — Go's standard library has a `strings` package full of ready-made helpers for text. You import it next to `fmt` and call …
- Tidy up messy input — Text typed by people is messy: extra spaces, random capitals. `strings.TrimSpace(s)` removes spaces, tabs and newlines f…
- Replace and Repeat — `strings.ReplaceAll(s, old, new)` swaps every occurrence of `old` for `new`. (`strings.Replace` does the same but takes …
- Split and Join — `strings.Split(s, sep)` cuts a string into a `[]string` wherever `sep` appears. `strings.Join(parts, sep)` does the oppo…
- Fields: split into words — `strings.Split(s, " ")` splits on every single space, so double spaces and the spaces at the ends produce empty strings.…
- Build strings with strings.Builder — Because strings are immutable, `s += "more"` in a loop creates a brand-new string every time. A `strings.Builder` collec…
- Bytes vs runes — A Go string is a sequence of **bytes**, stored as UTF-8. Plain English letters take one byte each, but a character like …
- Reverse a title with runes — To work with characters instead of bytes, convert the string to a slice of runes with `[]rune(s)`, and convert back with…
- strconv: numbers and text — You cannot glue a number onto a string with `+`, and `string(12)` does not give you `"12"` (it treats 12 as a rune, and …
- Convert safely with Atoi — Text from people and files is often not a valid number. When `strconv.Atoi` can't convert a string, it returns `0` and a…
Go Strings and strconv concepts covered
- Working with text