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
Linda HamiltonOriginal
2024-11-19 21:42:02729browse

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))
}

Output:

'a'

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))

Output:

a

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))
}

Output:

a
b
c

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

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

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:
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