Golang Alphabetic representation of a number

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


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


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