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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete