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

How to Convert a Rune to a String in Go?

Linda Hamilton
Release: 2024-11-19 21:42:02
Original
743 people have browsed it

How to Convert a Rune to a String in Go?

Converting Rune to String in Golang

To convert a rune to a string, you can use the strconv.QuoteRune() function. However, in your code, you're using scanner.Scan() to read a rune, which is incorrect.

The scanner.Scan() function reads tokens or runes of special tokens controlled by the Scanner.Mode bitmask. It does not return the rune itself but special constants from the text/scanner package.

To read a single rune, use Scanner.Next() instead. Here's the corrected code:

package main

import (
    "fmt"
    "strconv"
    "strings"
    "text/scanner"
)

func main() {
    var b scanner.Scanner
    const a = `a`
    b.Init(strings.NewReader(a))
    c := b.Next()
    fmt.Println(strconv.QuoteRune(c))
}
Copy after login

Output:

'a'
Copy after login

Alternatively, you can directly convert a rune to a string using type conversion, as rune is an alias for int32:

r := rune('a')
fmt.Println(string(r))
Copy after login

Output:

a
Copy after login

For more convenience, you can iterate over the runes of a string using the for ... range construct:

for _, r := range "abc" {
    fmt.Println(string(r))
}
Copy after login

Output:

a
b
c
Copy after login

You can also convert a string to a slice of runes using []rune():

runes := []rune("abc")
fmt.Println(runes) // Output: [97 98 99]
Copy after login

Finally, you can use utf8.DecodeRuneInString() to extract a rune from a string.

The above is the detailed content of How to Convert a Rune to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

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