Home > Backend Development > Golang > How to Convert a Rune to a String in Golang?

How to Convert a Rune to a String in Golang?

Linda Hamilton
Release: 2024-11-20 03:50:01
Original
708 people have browsed it

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))
Copy after login

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))
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template