Learn/Go/8. Strings and a small project
Lesson 8 of 15
Sign in

Go, lesson 8

Strings and a small project

Text is everywhere: names, commands, file contents. A Go string is an immutable sequence of bytes, usually holding UTF-8 text. Immutable means you never change a string in place; you build a new one.

Everyday operations

The strings package does most of the work. A few favourites:

Splitting and joining are the bread and butter of text processing:

+ joins two strings, and fmt.Sprintf builds a string with the same verbs as Printf but returns it instead of printing it.

Bytes and runes

len(s) counts bytes, not letters. That matters as soon as text leaves plain English: len("café") is 5, because takes two bytes in UTF-8. Indexing also gives a byte.

2 exercises to try what you just read.

Exercise 1

Initials

Press Ctrl Enter or Check to test your code.

Exercise 2

Word stats

Press Ctrl Enter or Check to test your code.

é
s[i]

A single Unicode character is called a rune in Go (type rune, written with single quotes: 'é'). Ranging over a string walks it rune by rune, and the index jumps over multi-byte characters:

To count characters use utf8.RuneCountInString(s), or convert to a rune slice with []rune(s), which also lets you index characters. The unicode package classifies runes: unicode.IsLetter(r), unicode.IsDigit(r), unicode.ToUpper(r).

Building strings efficiently

Because strings are immutable, adding to one in a loop creates a new string every time. For long outputs, use a strings.Builder, which grows a buffer and produces the final string once:

Converting numbers and text

strconv.Itoa(42) gives "42", and strconv.Atoi("42") goes the other way. fmt.Sprint(x) turns any value into its default text form.

Putting it together

The second exercise is a small project. It uses input reading (lesson 3), decisions and loops (4 and 5), a helper function (6), a slice and a map (7) and the string tools from this lesson. To read the whole input at once, io.ReadAll(os.Stdin) returns every byte as a []byte, which string(data) turns into text. Plan it in steps before you type: read all the text, split it into words, clean each word, then compute and print each statistic.

Further reading

  • Package strings
  • Go blog: Strings, bytes, runes and characters in Go
  • Package unicode

Read one line containing a full name (any number of words, separated by one or more spaces). Print the initials in uppercase, each followed by a dot, with no spaces.

Sample input:

Sample output:

Read all of the input (it may span several lines). Split it into words on whitespace. Clean each word by making it lowercase and removing every character that is not a letter; skip words that become empty. Then print:

If there are no words at all, print only words: 0.

Sample input:

Sample output:

s := "  Hello, Gopher!  "
strings.TrimSpace(s)                 // "Hello, Gopher!"
strings.ToUpper("go")                // "GO"
strings.Contains("seafood", "foo")   // true
strings.HasPrefix("golang", "go")    // true
strings.Index("chicken", "ken")      // 4 (or -1 if missing)
strings.ReplaceAll("a-b-c", "-", "+") // "a+b+c"
strings.Repeat("ab", 3)              // "ababab"
strings.Split("a,b,c", ",")            // ["a" "b" "c"]
strings.Fields("  two   words ")       // ["two" "words"] (splits on any whitespace)
strings.Join([]string{"x", "y"}, "-")  // "x-y"
for i, r := range "café" {
	fmt.Println(i, string(r))
}
// 0 c, 1 a, 2 f, 3 é
var b strings.Builder
for i := range 3 {
	fmt.Fprintf(&b, "%d;", i)
}
b.WriteString("end")
fmt.Println(b.String()) // 0;1;2;end
ada  king lovelace
A.K.L.
words: <number of cleaned words>
unique: <number of different cleaned words>
longest: <the longest cleaned word; if several tie, the one that appeared first>
top: <the most frequent word; if several tie, the one that appeared first> (<count>)
The cat sat. The CAT ran!
A dog? The end.
words: 10
unique: 7
longest: the
top: the (3)