Home > Mobile >  golang for loop a string, but it prints 'char' as int, why?
golang for loop a string, but it prints 'char' as int, why?

Time:08-17

A very simple go function:

func genString(v string) {
    for _, c := range v {
        fmt.Println(c)
    }
}

Called in:

func TestBasics(t *testing.T) {
    genString("abc")
}

Then I ran:

go test -v -run TestBasics xxxxxx

It prints:

97
98
99

I expected that it should print

a
b
c

But it prints the corresponding integer value? Why, how to fix it and print just the char?

Thanks!

CodePudding user response:

change the function gen string to `func genstring(v string) { for _, c := range v { fmt.Println(string(c))

  }

}`

CodePudding user response:

Why

Looping with range over string will give you a sequence of runes.

For range spec:

Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
string          s  string type            index    i  int    see below  rune
map             m  map[K]V                key      k  K      m[k]       V
channel         c  chan E, <-chan E       element  e  E

(notice the second row and last column in the table)

  1. 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.

A rune value is an integer value identifying a Unicode code point.
The type itself is just an alias of int32.


how to fix it and print just the char

Use fmt.Printf with the %c verb to print the character value, i.e. fmt.Printf("%c\n", c)

fmt printing verbs doc:

Integers:

%b  base 2
%c  the character represented by the corresponding Unicode code point
%d  base 10
%o  base 8
%O  base 8 with 0o prefix
%q  a single-quoted character literal safely escaped with Go syntax.
%x  base 16, with lower-case letters for a-f
%X  base 16, with upper-case letters for A-F
%U  Unicode format: U 1234; same as "U X"

(notice the second row in the table)


for _, c := range "abc" {
    fmt.Printf("%c\n", c)
}

https://go.dev/play/p/BEjJof4XvIk

  • Related