Reputation:
http://play.golang.org/p/ZsALO8oF3W
I want to traverse a string and return the character values. How do I, not return the numeric values per each letter, and return the actual characters?
Now I am getting this
0 72 72
1 101 101
2 108 108
3 108 108
4 111 111
My desired output would be
0 h h
1 e e
2 l l
3 l l
4 o o
package main
import "fmt"
func main() {
str := "Hello"
for i, elem := range str {
fmt.Println(i, str[i], elem)
}
for elem := range str {
fmt.Println(elem)
}
}
Thanks,
Upvotes: 30
Views: 50455
Reputation: 166569
For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type rune, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.
For example,
package main
import "fmt"
func main() {
str := "Hello"
for _, r := range str {
c := string(r)
fmt.Println(c)
}
fmt.Println()
for i, r := range str {
fmt.Println(i, r, string(r))
}
}
Output:
H
e
l
l
o
0 72 H
1 101 e
2 108 l
3 108 l
4 111 o
Upvotes: 58
Reputation: 7397
package main Use Printf to indicate you want to print characters.
import "fmt"
func main() {
str := "Hello"
for i, elem := range str {
fmt.Printf("%d %c %c\n", i, str[i], elem)
}
}
Upvotes: 6
Reputation: 11377
The way you are iterating over the characters in the string is workable (although str[i] and elem are the duplicative of each other). You have the right data.
In order to get it to display correctly, you just need to output with the right formatting (i.e. interpreted as a unicode character rather than an int).
Change:
fmt.Println(i, str[i], elem)
to:
fmt.Printf("%d %c %c\n", i, str[i], elem)
%c
is the character represented by the corresponding Unicode code point per the Printf doc: http://golang.org/pkg/fmt/
Upvotes: 2