增加字母表

我正在尝试创建一个函数,它将在传递索引时为我提供字母位置。 它会像excel显示它的列一样。 A … Z,AA,AB ….我写了下面的函数来得到Z的结果。它看起来像

static string GetColumnName(int index) { const int alphabetsCount = 26; if (index <= alphabetsCount) { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } return string.Empty; } 

这工作正常,直到’Z’。 如果我通过1则返回’A’,如果我通过2则返回’B’,依此类推。 但是,当我将27传递给这个函数时,我无法弄清楚如何获得AA。 我想我需要一个递归方法来找到它。

对这个问题的任何输入都会很棒!

编辑

这是Tordek建议的。 但他的代码将失败,如52,78等数字。为此添加了解决方法,这是最终的工作代码。

 static string GetColumnName(int index) { const int alphabetsCount = 26; if (index > alphabetsCount) { int mod = index % alphabetsCount; int columnIndex = index / alphabetsCount; // if mod is 0 (clearly divisible) we reached end of one combination. Something like AZ if (mod == 0) { // reducing column index as index / alphabetsCount will give the next value and we will miss one column. columnIndex -= 1; // passing 0 to the function will return character '@' which is invalid // mod should be the alphabets count. So it takes the last char in the alphabet. mod = alphabetsCount; } return GetColumnName(columnIndex) + GetColumnName(mod); } else { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } } 

任何递归函数都可以转换为等效的迭代函数。 我发现首先递归思考总是很容易:

 static string GetColumnName(int index) { const int alphabetsCount = 26; if (index > alphabetsCount) { return GetColumnName(index / alphabetsCount) + GetColumnName(index % alphabetsCount); } else { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } } 

哪个可以简单转换成:

 static string GetColumnName(int index) { const int alphabetsCount = 26; string result = string.Empty; while (index > 0) { result = char.ConvertFromUtf32(64 + (index % alphabetsCount)) + result; index /= alphabetsCount; } return result; } 

即便如此,请听乔尔。

看到这个问题:
将列索引转换为Excel列名

或者这一个:
如何将列号(例如127)转换为excel列(例如AA)

虽然第一个链接在顶部有正确答案,而第二个链接有几个不正确。

递归是一种可能性 – 如果index > 26 ,则在此调用中处理index % 26并将其连接到index / 26上的递归调用。 但是,迭代通常更快,并且不难安排这样的简单情况。 在伪代码中:

 string result =  while index > 26: index = index / 26 result =  + result return result 

等等。

静态字符串GetColumnName(int index)
 {
     const int alphabetsCount = 26;
     string result ='';

     if(index> = alphabetsCount)
     {
        结果+ = GetColumnName(index-alphabetsCount)
     }
     return(string)(64 + index);
 }

我的C#是可怕的和可怜的。 把它解释为伪代码 – 它几乎肯定不会编译,但可能会让你开始。

我不想在C#中回答这个问题,但我将向您展示这在Haskell中是多么容易。

 alphas :: [String] alphas = [x ++ [c] | x <- ([]:alphas), c <- ['A'..'Z']] Prelude> take 100 alphas ["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","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK", "AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA", "BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ", "BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG", "CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV"]