18

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

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

1
  • two options - create an array of all the letters and get it's index+1 from an array. Second - use ascii table and subtract needed number. Commented Apr 22, 2016 at 22:15

4 Answers 4

36

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

Sign up to request clarification or add additional context in comments.

3 Comments

Might be a dumb question but how did you know that you could add a number to a constant character ( "A" ) to navigate the characters? Is this something in most languages, go specific, or rune specific? Never messed with rune() before...
@afreeland rune in Go is an alias for int32. If you have a constant like 'A', that is equivalent to a value 65. The types rune and int32 are one and the same, completely interchangable. So when you write 'A' + 1, it's the same as if you'd write 65 + 1.
Awesome, thanks for breaking it down a little further for me...I feel much better now =)
6

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

Comments

4

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.