How to iterate over all the characters of the string in Go Language
In Go Language, a string is a slice of bytes. The bytes of the strings can be defined in the Unicode text using UTF-8 encoding. UTF-8 is based on 8-bit code units. Each character is encoded as 1 to 4 bytes. The first 128 Unicode code points are encoded as 1 byte in UTF-8.
Output:
Output:
Output:
For Example,
package main
import "fmt"
func main() {
text := "aπ"
fmt.Println(len(text))
}
3
Here the length of the String is 3 because,
- ‘a’ takes one byte as per UTF-8
- ‘π’ takes two bytes as per UTF-8
So we cannot use for loop to iterate over all the characters of the string because it will iterate over bytes and not characters. This means it will iterate three times and the print value corresponding to a byte at that index.
How to iterate over all the characters of the string in Go Language?
- Iterate over a string by runes
- Iterate over a string by for-range loop
Iterate over a string by runes
Go allows us to easily convert a string to a slice of runes and then iterate over that.
For Example,
package main
import "fmt"
func main() {
text := "aπ日"
fmt.Println("string length:", len(text))
runes := []rune(text)
//Iterate
for i := 0; i < len(runes); i++ {
fmt.Println(string(runes[i]))
}
}
string length: 6
a
π
日
Iterate over a string by for-range loop
For Example,
package main
import "fmt"
func main() {
text := "aπ界"
fmt.Println("string length:", len(text))
for _, char := range text {
fmt.Println(string(char))
}
}
string length: 6
a
π
日