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/utf8package also providesutf8.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:
func jumlahKarakter(pesan string) int: the number of characters (runes), not bytes.func jumlahVokal(pesan string) int: the number of vowelsa i u e o, both lowercase and uppercase.func adaEmoji(pesan string) bool:trueif 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.