How to iterate through a string in Golang

In this shot, we will learn how to iterate through a string in Golang.

We can use the following methods to iterate through a string:

  • for loop
  • for-range loop

The for loop method

There are two steps to follow for this method:

  • Find the length of the string.
  • Use a for loop to get each character at the present index.

Implementation

package main
//import fmt package
import(
"fmt"
)
//Program execution starts here
func main(){
//provide the string
str:= "Educative"
//iterate through the string
for i:=0; i<len(str); i++{
//print each character in new line
fmt.Printf("%c\n", str[i])
}
}

Explanation

In the code snippet above:

  • In line 5, we import the fmt package.
  • In line 9, the execution of the program starts from the main() function.
  • In line 12, we declare the string str with shorthand syntax and assign the value Educative to it.
  • In line 15, we use a for loop to iterate through the string.
    • We use the len() method to calculate the length of the string and use it as a condition for the loop.
  • In line 18, we use the index i to print the current character.

The for-range loop method

The for-range loop returns two values in each iteration:

  • Index: the index of the current iteration.
  • Character: the character at the present index in the string.

Implementation

package main
//import fmt package
import(
"fmt"
)
//Program execution starts here
func main(){
//provide the string
str:= "Educative"
//iterate through the string
for _, character := range str {
//print each character in new line
fmt.Printf("%c\n", character)
}
}

Explanation

The explanation is the same as the for loop method except for the following differences:

  • In line 15, we use the for-range loop to iterate through the string.
  • Since we are not using index returned by range, we can use _ in its place.
  • In line 18, we print each character in a new line.

Free Resources