How to Represent Numbers as Alphabetic Characters in Go?

Susan Sarandon
Release: 2024-11-05 04:35:02
Original
978 people have browsed it

How to Represent Numbers as Alphabetic Characters in Go?

English Alphabetic Representation of a Number

In Go, there are several methods to convert numbers into alphabetic characters.

Rune Conversion

Add the number to the constant 'A' - 1 to convert it to a rune. For instance, 3 becomes 'C', and 23 becomes 'W'.

<code class="go">import "fmt"

func toChar(i int) rune {
    return rune('A' - 1 + i)
}

func main() {
    for _, i := range []int{1, 2, 23, 26} {
        fmt.Printf("%d %q\n", i, toChar(i))
    }
}</code>
Copy after login

String Conversion

To get the alphabetic representation as a string, use:

<code class="go">func toCharStr(i int) string {
    return string('A' - 1 + i)
}

func main() {
    for _, i := range []int{1, 2, 23, 26} {
        fmt.Printf("%d \"%s\"\n", i, toCharStr(i))
    }
}</code>
Copy after login

Cached String Conversion

For repeated conversions, consider caching the strings in an array:

<code class="go">var arr = [...]string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}

func toCharStrArr(i int) string {
    return arr[i-1]
}

func main() {
    for _, i := range []int{1, 2, 23, 26} {
        fmt.Printf("%d \"%s\"\n", i, toCharStrArr(i))
    }
}</code>
Copy after login

String Constant Slicing

Another efficient option is to slice a constant string:

<code class="go">const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

func toCharStrConst(i int) string {
    return abc[i-1 : i]
}

func main() {
    for _, i := range []int{1, 2, 23, 26} {
        fmt.Printf("%d \"%s\"\n", i, toCharStrConst(i))
    }
}</code>
Copy after login

The above is the detailed content of How to Represent Numbers as Alphabetic Characters in Go?. 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