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 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]))
}
}
Output:
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))
}
}
Output:
string length: 6
a
π
日

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example