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
π
日

Comments

Popular posts from this blog

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

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

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

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example