patterncsharpMajor
Integer to Alphabet string ("A", "B", ...."Z", "AA", "AB"...)
Viewed 0 times
alphabetstringinteger
Problem
So this question is prompted by two things.
So when I thought about this problem this popped into my head almost immediately.
My question is this: Is this approach a better solution (performance wise)?
or is a recursive / computed value better (eg. this answer )?
- I found some code in our source control doing this sort of things.
- These SO questions:
- https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name
- https://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c-sharp
- https://stackoverflow.com/questions/4075656/how-to-get-continuous-characters-in-c/4077835#4077835
- https://stackoverflow.com/questions/1011732/iterating-through-the-alphabet-c-sharp-a-caz
So when I thought about this problem this popped into my head almost immediately.
class Util
{
private static string[] alphabetArray = { string.Empty, "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" };
public static IEnumerable alphaList = alphabetArray.Cast();
public static string IntToAA(int value)
{
while (Util.alphaList.Count() -1
Util.alphabetArray.Skip(1).Select(innerLetter => currentLetter + innerLetter)
)
);
}
}
My question is this: Is this approach a better solution (performance wise)?
or is a recursive / computed value better (eg. this answer )?
Solution
Math! Simple math is certainly the nicest way, no lists to deal with, just old fashion ASCII and math. If you want to be able to toggle the capitalization of this method, simply use a ternary operator like this
Edit: To meet the requirement of A being 1 instead of 0, I've added
isCapital ? 'A' : 'a' I just left it capital as that is how the OP seemed to want it. Jeff Mercado's Answer explained well enough the differences between calculated, recursive and such... I mostly wanted to provide a simplistic calculated answer that did not involve using lists.public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26 ) + result;
value /= 26;
}
return result;
}Edit: To meet the requirement of A being 1 instead of 0, I've added
-- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.Code Snippets
public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26 ) + result;
value /= 26;
}
return result;
}Context
StackExchange Code Review Q#13105, answer score: 33
Revisions (0)
No revisions yet.