Home  >  Article  >  Backend Development  >  How to Represent Numbers as Alphabetic Characters in Go?

How to Represent Numbers as Alphabetic Characters in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 04:35:02906browse

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>

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>

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>

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>

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!

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