Go course

LoopsLooping over Strings and Runes

Go

Display

Theme

Loops · Test exercise

Looping over Strings and Runes

A string in Go is a sequence of bytes holding UTF-8 encoded text. A plain Latin letter takes 1 byte, but characters like é, ñ, Japanese characters, or emoji take 2–4 bytes.

s := "kopi☕"
fmt.Println(len(s)) // 7, bukan 5! (☕ memakan 3 byte)

len counts bytes, not characters. That's why the comment above says 7, not 5: ☕ takes 3 bytes.

range over a string

When you range over a string, Go decodes the UTF-8 for you and gives you each rune (one Unicode character, type rune = int32) along with its starting byte index:

for i, r := range "kopi☕" {
	fmt.Printf("%d: %c\n", i, r)
}
// 0: k
// 1: o
// 2: p
// 3: i
// 4: ☕

Notice how the index jumps according to the number of bytes in each character. To count the characters, count how many times the loop runs:

jumlah := 0
for range s {
	jumlah++
}

The unicode/utf8 package also provides utf8.RuneCountInString(s), which does the same thing.

Comparing runes

Rune literals are written with single quotes: 'a', 'Z', '☕'. You can compare them directly or use a switch:

switch r {
case 'a', 'i', 'u', 'e', 'o':
	fmt.Println("vokal")
}

Task

A chat app shows message statistics before a message is sent. Complete:

  1. func jumlahKarakter(pesan string) int: the number of characters (runes), not bytes.
  2. func jumlahVokal(pesan string) int: the number of vowels a i u e o, both lowercase and uppercase.
  3. func adaEmoji(pesan string) bool: true if the message contains at least one rune with a value >= 0x1F300 (the common emoji range). Stop checking as soon as you find one.

Example: jumlahKarakter("Halo 👋") = 6, jumlahVokal("Selamat Pagi") = 5, adaEmoji("Halo 👋") = true.

main.go
package main

import "fmt"

func jumlahKarakter(pesan string) int {
	// TODO: hitung rune, bukan byte
	return len(pesan)
}

func jumlahVokal(pesan string) int {
	// TODO: hitung a, i, u, e, o (huruf kecil dan kapital)
	return 0
}

func adaEmoji(pesan string) bool {
	// TODO: true jika ada rune >= 0x1F300
	return false
}

func main() {
	pesan := "Halo 👋 sampai jumpa di kafé"
	fmt.Println("Karakter:", jumlahKarakter(pesan))
	fmt.Println("Vokal:", jumlahVokal(pesan))
	fmt.Println("Ada emoji:", adaEmoji(pesan))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)