Home > Article > Backend Development > How to Convert a Rune to a String in Golang?
Converting Rune to String in Golang
You have a concern regarding casting a rune into a string and printing it, encountering undefined characters. Let's delve into the issue and find a solution.
Firstly, in your original code, you used Scanner.Scan() to read a rune. However, this method is designed to handle tokens or runes with special token values, not the actual read rune itself.
To read a single rune, you should instead use Scanner.Next():
c := b.Next() fmt.Println(c, string(c), strconv.QuoteRune(c))
This code will now correctly read and print the rune as an integer, its character representation, and its quoted version.
Alternatively, if you want to simply convert a rune to a string, you can use a straightforward type conversion. Rune is an alias for int32, and converting integer numbers to strings generates their UTF-8 representation.
r := rune('a') fmt.Println(r, string(r))
To iterate over the runes of a string, you can use a for ... range loop:
for i, r := range "abc" { fmt.Printf("%d - %c (%v)\n", i, r, r) }
You can also convert a string to a slice of runes using []rune("abc").
Another option is to use utf8.DecodeRuneInString().
In your original code using Scanner.Scan(), you inadvertently configured the scanner's mode to handle Go tokens, which include identifiers like "a". Calling Scan() then returned scanner.Ident and printed the identifier's text, resulting in the undefined characters.
The above is the detailed content of How to Convert a Rune to a String in Golang?. For more information, please follow other related articles on the PHP Chinese website!