Golang数字的字母表示

huangapple go评论161阅读模式
英文:

Golang Alphabetic representation of a number

问题

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

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

英文:

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

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

答案1

得分: 33

简单起见,下面的解决方案中省略了范围检查。可以在Go Playground上尝试它们。

数字 -> rune

只需将数字添加到常量'A' - 1,例如添加1得到'A',添加2得到'B'等等:

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

测试代码:

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

输出结果:

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

数字 -> string

或者,如果你想要一个string类型的结果:

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

输出结果:

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

这最后一个(将数字转换为string)在规范:转换到和从字符串类型中有详细说明:

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

数字 -> string(缓存)

如果你需要多次执行此操作,将strings存储在数组中并从中返回string会更高效:

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

注意:使用切片(而不是数组)也可以。

注意2:如果你在数组中添加一个虚拟的第一个字符,这样你就不必从i中减去1

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

数字 -> string(切片一个string常量)

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

const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

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

切片一个string是高效的:新的string将共享底层数组(这是因为string是不可变的)。

英文:

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

Number -> rune

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

Testing it:

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

Output:

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

Number -> string

Or if you want it as a string:

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

Output:

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

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

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

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.

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 (slicing a string constant)

Also another interesting solution:

const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

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

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

答案2

得分: 6

如果你不需要一个符文,而是一个字符串,并且需要超过一个字符,例如 Excel 列:

package main

import (
	"fmt"
)

func IntToLetters(number int32) (letters string){
	number--
	if firstLetter := number/26; firstLetter > 0{
		letters += IntToLetters(firstLetter)
		letters += string('A' + number%26)
	} else {
		letters += string('A' + number)
	}
		
	return 
}

func main() {
	fmt.Println(IntToLetters(1))// 打印 A
	fmt.Println(IntToLetters(26))// 打印 Z
	fmt.Println(IntToLetters(27))// 打印 AA
	fmt.Println(IntToLetters(1999))// 打印 BXW
}

预览链接:https://play.golang.org/p/GAWebM_QCKi

我还创建了一个包含此代码的包:https://github.com/arturwwl/gointtoletters

英文:

If you need not a rune, but a string and also more than one character for e.g. excel column

package main

import (
	"fmt"
)

func IntToLetters(number int32) (letters string){
	number--
	if firstLetter := number/26; firstLetter >0{
		letters += IntToLetters(firstLetter)
		letters += string('A' + number%26)
	} else {
		letters += string('A' + number)
	}
		
	return 
}

func main() {
	fmt.Println(IntToLetters(1))// print A
	fmt.Println(IntToLetters(26))// print Z
	fmt.Println(IntToLetters(27))// print AA
	fmt.Println(IntToLetters(1999))// print BXW
}

preview here: https://play.golang.org/p/GAWebM_QCKi

I made also package with this: https://github.com/arturwwl/gointtoletters

答案3

得分: 3

最简单的解决方案是:

func stringValueOf(i int) string {
   var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   return string(foo[i-1])
}

希望这能帮助你解决问题。编程愉快!

英文:

The simplest solution would be

func stringValueOf(i int) string {
   var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   return string(foo[i-1])
}

Hope this will help you to solve your problem. Happy Coding!!

答案4

得分: 0

如果你想表示一个大于26(Z)的数字,这是最简单的解决方案。试试看。

func convertToAlphabetic(n int) string {
    result := ""
    for n > 0 {
        mod := (n - 1) % 26
        result = string('A'+mod) + result
        n = (n - mod) / 26
    }
    return result
}

示例结果:

  • 3: C
  • 32: AF
  • 876: AGR
英文:

If you want to represent a number bigger than 26(Z), this is the simplest solution. Give a try.

func convertToAlphabetic(n int) string {
	result := ""
	for n > 0 {
		mod := (n - 1) % 26
		result = string('A'+mod) + result
		n = (n - mod) / 26
	}
	return result
}

Example results:

  • 3: C
  • 32: AF
  • 876: AGR

huangapple
  • 本文由 发表于 2016年4月23日 06:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/36803999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定