Go strings can be seen as a sequence of bytes, or as a sequence of runes. This section shows how you can iterate a string either way.
How to do it...
To iterate the bytes of a string, use indexes:
for i:=0;i<len(str);i++ {
fmt.Print(str[i]," ")
}
To iterate the runes of a string, use range
:
for index, c:=range str {
fmt.Print(c," ")
}
How it works...
A Go string is a slice of bytes, so you would expect to be able to write a for-loop to iterate the bytes and runes of a string. You might think that you can do the following:
strBytes := []byte(str)
strRunes := []rune(str)
However, converting a string to a slice of bytes or a slice of runes is an expensive operation. The first one creates a writeable copy of the bytes of the str
string, and the second one creates a writeable copy of the runes of str
. Remember that rune
is uint32
.
There are two forms of for-loop to iterate the...