gpt4 book ai didi

c# - 如何像在 excel 列中一样创建字母表

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:30:32 25 4
gpt4 key购买 nike

我尝试创建一个 Alphabet 系列,例如a,b,c,...z,aa,ab,ac,ad,ae,af,...,az,ba,bb,bc,...,bz,..zz,aaa, aab,aac..直到给定的 number(N)

但是当我尝试使用 for 循环 创建它时,我在元素中的每个第二个字符创建了一个 for 循环这意味着打印 a..z - loop1, aa 每隔一个字母 a ,我写一个新的 for 循环

是否可以用 for 循环创建这种类型系列...

提前致谢...

最佳答案

方法如下:

    public static string GetExcelColumnName(int index)
{
int d = index;
string name = "";
int mod;

while (d > 0)
{
mod = (d - 1) % 26;
name = Convert.ToChar('a' + mod).ToString() + name;
d = (int)((d - mod) / 26);
}

return name;
}

public static IEnumerable<string> GetExcelColumns(int n) {
for (int i = 1; i <= n; i++)
{
yield return GetExcelColumnName(i);
}
}

static void Main(string[] args)
{
int i = 1;
foreach (var item in GetExcelColumns(900))
{
Console.Write(i++ + ": " + item + " ");
}
Console.WriteLine();
}

GetExcelColumnName的解释:

//Suppose index = 1, `GetExcelColumnName` should return `"a"`.
d = 1
d > 0
mod = (d - 1) % 26; //mod now is 0
Convert.ToChar('a' + mod); // => That's 'a'
//name now is "a"
d = (d - mod) / 26 = (1 - 0) / 26 = 0 // d is now 0
//End of While
method returns "a"

//Suppose index = 28, `GetExcelColumnName` should return `"ab"`.
d = 28
d > 0
mod = (d - 1) % 26; //mod now is 1 (27 modulo 26)
Convert.ToChar('a' + mod); // => That's 'b'
//name now is "b"
d = (d - mod) / 26 = (28 - 1) / 26 = 1 // d is now 1
d > 0
mod = (d - 1) % 26; //mod now is 0 (0 modulo 26)
Convert.ToChar('a' + mod); // => That's 'a'
//name now is "ab"
d = (d - mod) / 26 = (1 - 0) / 26 = 0 // d is now 0
//End of While
method returns "ab"

关于c# - 如何像在 excel 列中一样创建字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17185305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com