Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 147 Β· Collections

Working with Strings: strings, strconv and unicode

Learn Go string handling - strings.Builder, Split, Join, Fields, Trim, Replace, Cut, EqualFold, Lines and SplitSeq, strconv Atoi and ParseFloat, Quote, and unicode checks, with efficiency tips.

Text processing is half of everyday programming: parsing a config line, cleaning user input, building a message, turning "42" into a number. In Go, a string is an immutable sequence of bytes (Strings, Bytes and Runes covers how that works). Because strings can't be changed in place, nearly every operation returns a new string, and the work is done by three standard packages:

  • strings: searching, splitting, joining, trimming, replacing and building strings.
  • strconv: converting between strings and numbers or booleans.
  • unicode: classifying individual characters (runes) as letters, digits, spaces and so on.

This lesson walks through the functions you'll use constantly, with a note about the Go version for the newer ones.

Searching and testing

These functions answer questions about a string without changing it. Almost all of them are case sensitive:

Go Searching in strings

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

strings.Index returns a byte position, not a character position, which only matters with non-ASCII text. strings.EqualFold compares with simple Unicode case folding, which is the right tool for case-insensitive equality; it's better than comparing ToLower results. Note that it doesn't treat ß as SS, because that is a special (multi-letter) case mapping.

Splitting and joining

strings.Split cuts a string at every separator and strings.Join glues a slice back together. strings.Fields splits around runs of whitespace, which is almost always what you want for words:

Go Split, Fields and Join

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Splitting a string that contains no separator returns a slice with that single string, and splitting "" returns [""] (one empty string). Use Fields rather than Split(s, " ") to ignore repeated spaces.

Cut: the cleanest way to split once

strings.Cut(s, sep) splits at the first separator and reports whether it found one. It's usually clearer than Index plus slicing for key=value or host:port text. Go 1.20 added CutPrefix and CutSuffix that remove a known prefix or suffix:

Go Cut, CutPrefix and CutSuffix

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Trimming, replacing and changing case

The Trim family removes characters from the ends of a string. Beware the classic trap: Trim, TrimLeft and TrimRight take a set of characters, not a prefix. To remove an exact prefix or suffix use TrimPrefix/TrimSuffix (or CutPrefix):

Go Trim, Replace and case conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The two lines show the trap. TrimPrefix("peer-review", "pe") removes the exact text pe once and leaves er-review. TrimLeft("peer-review", "pe") treats "pe" as the set {p, e} and strips leading characters from it until one is not in the set, leaving r-review. Pick the function that says what you mean.

A strings.Replacer replaces many patterns in one pass and is the right tool for escaping.

There is no standard "title case" function that works for all languages. strings.Title is deprecated, because it mishandles punctuation and apostrophes. For correct capitalization of names, use the golang.org/x/text/cases package from the extended library. To capitalize the first letter of simple ASCII text, uppercase the first rune yourself.

Building strings efficiently

Because strings are immutable, s += "x" in a loop allocates a brand-new string every time, copying all earlier characters. For a few concatenations that's fine; for thousands it becomes quadratic. Use strings.Builder, which keeps a growing byte buffer and produces the string once at the end:

Go strings.Builder versus +=

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Don't copy a strings.Builder after you start using it; it detects this and panics. Keep it in a variable or behind a pointer. For joining a ready-made slice, strings.Join is simplest and also allocates once.

Looping over lines and pieces (Go 1.24)

strings.Split builds a whole slice before you can look at the first piece. Go 1.24 added iterator versions that produce pieces one at a time without that slice: strings.Lines, strings.SplitSeq, strings.FieldsSeq and a few siblings. You use them directly in a for range loop (see Iterators):

Go Lines, SplitSeq and FieldsSeq

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that Lines keeps the newline at the end of each line, so trim it with strings.TrimSuffix(line, "\n") when you don't want it. On older Go versions use strings.Split(text, "\n") or a bufio.Scanner.

Converting with strconv

fmt.Sprint(42) works, but strconv is faster and more precise, and it's the only way to convert from strings with proper error handling. Itoa and Atoi handle int; ParseInt, ParseUint and ParseFloat take a base and a bit size; ParseBool accepts 1, t, T, TRUE, true, True and the false equivalents:

Go Parsing and formatting numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The errors are of type *strconv.NumError, and they tell you the function, the input and the reason (strconv.ErrSyntax or strconv.ErrRange). Always check them; the number returned alongside an error is a best-effort value, such as the maximum value on overflow. Never ignore the error on input you didn't write yourself. Atoi("") is also a syntax error.

Quoting

strconv.Quote produces a Go string literal with escapes, and Unquote reverses it. Together with %q from fmt they make invisible characters visible in logs and tests:

Go Quote and Unquote

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Classifying characters with unicode

The unicode package works on single runes. Loop over a string with range to get runes (not bytes), then test each one:

Go unicode checks and strings.Map

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

unicode.IsLetter recognizes letters of every script, not just A-Z, which is why â and ß are counted. See Unicode and Text Processing for normalization, UTF-8 helpers and the limits of per-rune thinking.

A tour of the rest of strings and unicode

The functions above cover most daily work. These are the siblings you will reach for sooner or later, grouped by what they do.

Go Comparing, searching and splitting variations

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

EqualFold compares with Unicode simple case folding, which handles most scripts but not special expansions such as the German ß to SS (so the second result is false). Compare returns -1, 0 or 1, but the operators <, == and > do the same job, so you rarely need it. The Index family returns a byte offset, or -1 when nothing matches: IndexByte and IndexRune look for one character, IndexAny for any character of a set, and IndexFunc for the first rune that makes a function return true. SplitN stops after n pieces (the last piece keeps the rest), SplitAfter keeps the separators, and FieldsFunc splits wherever a function says so.

Trimming and mapping with functions

Go Trim*Func, Map and ToValidUTF8

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

TrimFunc, TrimLeftFunc and TrimRightFunc remove runes from the ends as long as the function returns true. strings.Map applies a function to each rune and drops the rune when you return a negative value, which makes it a tidy filter (here it also rotates letters by 13 places, so hello world becomes uryybjbeyq, the space being dropped). ToValidUTF8 replaces each run of invalid bytes with one replacement string.

The unicode package offers more than IsLetter: IsDigit and IsNumber, IsSpace, IsPunct, IsSymbol, IsControl, IsPrint, IsUpper and IsLower, plus ToUpper, ToLower and ToTitle for case mapping of single runes. For scripts there are range tables such as unicode.Han and unicode.Latin, used with unicode.Is(unicode.Han, r).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does strings.Split("a,b,,c", ",") return?

    Split keeps empty pieces, so there are four elements and the third is the empty string. strings.Fields would skip empties for whitespace.
  2. 2. What is the difference between strings.TrimPrefix(s, "ab") and strings.TrimLeft(s, "ab")?

    TrimLeft treats its second argument as a set of characters to strip repeatedly; TrimPrefix removes one exact prefix.
  3. 3. Why use strings.Builder instead of s += x in a loop?

    String concatenation allocates a new string every time. Builder grows one buffer and creates the final string once.
  4. 4. What does strconv.Atoi("3.5") return?

    Atoi parses only integers. The dot makes the input invalid, so it returns 0 and a *strconv.NumError.
  5. 5. What does key, value, found := strings.Cut("a=b=c", "=") give for value?

    Cut splits at the first separator only, so value is everything after it: b=c.

Summary

  • Strings are immutable: every strings function returns a new string.
  • Search with Contains, HasPrefix, HasSuffix, Index, Count, and compare case-insensitively with EqualFold.
  • Split keeps empty pieces; Fields splits on runs of whitespace; Cut, CutPrefix and CutSuffix split once.
  • Trim, TrimLeft and TrimRight take a character set; use TrimPrefix/TrimSuffix for exact text.
  • Build large strings with strings.Builder, not += in a loop.
  • strings.Lines, SplitSeq and FieldsSeq (Go 1.24) iterate without building a slice.
  • strconv converts to and from strings (Atoi, Itoa, ParseFloat, ParseBool, Quote). Always check its errors.
  • unicode classifies runes; loop with range to get runes, not bytes.

Next: Bytes, Buffers and Readers shows the mutable counterpart of strings and how Go streams data.