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
loopfor-range
loopfor
loop methodThere are two steps to follow for this method:
for
loop to get each character at the present index.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])}}
In the code snippet above:
fmt
package.main()
function.str
with shorthand syntax and assign the value Educative
to it.for
loop to iterate through the string.
len()
method to calculate the length of the string and use it as a condition for the loop.i
to print the current character.for-range
loop methodThe 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.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)}}
The explanation is the same as the for
loop method except for the following differences:
for-range
loop to iterate through the string.index
returned by range
, we can use _
in its place.