Alphabetic Representation of Numbers in Go
Converting a number to a letter in Golang can be achieved in several ways.
Number -> rune
Simply add the number to the constant 'A' - 1 to obtain the corresponding rune:
<code class="go">func toChar(i int) rune { return rune('A' - 1 + i) }</code>
Number -> String
If a string is desired, the following function can be used:
<code class="go">func toCharStr(i int) string { return string('A' - 1 + i) }</code>
Number -> String (Cached)
To optimize multiple conversions, the corresponding strings can be stored in an array and the array index used to retrieve the string:
<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] }</code>
Number -> String (Slicing String Constant)
An efficient solution involves slicing a string constant:
<code class="go">const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" func toCharStrConst(i int) string { return abc[i-1 : i] }</code>
These solutions provide convenient ways to convert numbers to their corresponding alphabetic representations in Go.
The above is the detailed content of How to Convert Numbers to Letters in Go?. For more information, please follow other related articles on the PHP Chinese website!