Golang 数字的字母表示 [英] Golang Alphabetic representation of a number

查看:29
本文介绍了Golang 数字的字母表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以将数字转换为字母?

Is there an easy way to convert a number to a letter?

例如,
3 => "C"23 => "W"?

For example,
3 => "C" and 23 => "W"?

推荐答案

为简单起见,以下解决方案省略了范围检查.
它们都可以在 Go Playground 上尝试.

For simplicity range check is omitted from below solutions.
They all can be tried on the Go Playground.

只需将数字添加到 const 'A' - 1 中,添加 1 即可得到 'A',添加 >2 你得到 'B' 等等:

Simply add the number to the const 'A' - 1 so adding 1 to this you get 'A', adding 2 you get 'B' etc.:

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

测试它:

for _, i := range []int{1, 2, 23, 26} {
    fmt.Printf("%d %q
", i, toChar(i))
}

输出:

1 'A'
2 'B'
23 'W'
26 'Z'

数字 -> 字符串

或者如果你想要它作为一个 string:

func toCharStr(i int) string {
    return string('A' - 1 + i)
}

输出:

1 "A"
2 "B"
23 "W"
26 "Z"

最后一个(将数字转换为 string)记录在 Spec: 字符串类型的转换:

This last one (converting a number to string) is documented in the Spec: Conversions to and from a string type:

将有符号或无符号整数值转换为字符串类型会生成一个包含整数的 UTF-8 表示形式的字符串.

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.

数字 -> 字符串(缓存)

如果您需要多次这样做,例如将 strings 存储在一个数组中并从中返回 string 是有利可图的:

Number -> string (cached)

If you need to do this a lot of times, it is profitable to store the strings in an array for example, and just return the string from that:

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

注意:切片(而不是数组)也可以.

Note: a slice (instead of the array) would also be fine.

注意#2:如果你添加一个虚拟的第一个字符,你可以改进这一点,这样你就不必从 i 中减去 1:

Note #2: you may improve this if you add a dummy first character so you don't have to subtract 1 from i:

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

Number -> string(切片一个 string 常量)

还有另一个有趣的解决方案:

Number -> string (slicing a string constant)

Also another interesting solution:

const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

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

string 进行切片是高效的:新的 string 将共享后备数组(可以这样做,因为 string 是不可变的).

Slicing a string is efficient: the new string will share the backing array (it can be done because strings are immutable).

这篇关于Golang 数字的字母表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆