OneBite.Dev - Coding blog in a bite size

loop through each character in a string in Go

Code snippet on how to loop through each character in a string in Go

package main

import "fmt"

func main() {
  s := "This is a string"
  for i := 0; i < len(s); i++ {
    fmt.Printf("%c\n", s[i])
  }
}

This code loops through every character of a given string. The variable “s” is set to “This is a string”. The for loop starts at 0, and stops when the variable “i” is equal to the length of “s”. In each iteration, the value of “i” increments by 1. The fmt.Printf function prints the character at the index of “i” from the string “s”. This will loop until all characters of “s” have been printed.

go