Posts

Showing posts with the label Iterate

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. For Example, package main import "fmt" func main() { text := "aπ" fmt.Println(len(text)) } Output: 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 t