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:
forloopfor-rangeloop
The for loop method
There are two steps to follow for this method:
- Find the length of the string.
- Use a
forloop to get each character at the present index.
Implementation
package main//import fmt packageimport("fmt")//Program execution starts herefunc main(){//provide the stringstr:= "Educative"//iterate through the stringfor i:=0; i<len(str); i++{//print each character in new linefmt.Printf("%c\n", str[i])}}
Explanation
In the code snippet above:
- In line 5, we import the
fmtpackage. - In line 9, the execution of the program starts from the
main()function. - In line 12, we declare the string
strwith shorthand syntax and assign the valueEducativeto it. - In line 15, we use a
forloop 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.
- We use the
- In line 18, we use the index
ito 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 packageimport("fmt")//Program execution starts herefunc main(){//provide the stringstr:= "Educative"//iterate through the stringfor _, character := range str {//print each character in new linefmt.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-rangeloop to iterate through the string. - Since we are not using
indexreturned byrange, we can use_in its place. - In line 18, we print each character in a new line.