Iterate over Characters of String

To iterate over characters of a string in Go language, we need to convert the string to an array of individual characters which is an array of runes, and use for loop to iterate over the characters.

In this tutorial, we will go through some examples where we iterate over the individual characters of given string.

Example

In the following example, we take a string in str, and iterate over its characters.

Example.go

package main

func main() {
	str := "ab£"
	chars := []rune(str)
	for i := 0; i < len(chars); i++ {
		char := string(chars[i])
		println(char)
	}
}

Inside the loop, we converted rune value to string using string() function.

Output

a
b
£
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to iterate over characters of a string in Go language, with example programs.