在 Java 中将字符递增到'Z'以上,就像电子表格一样



我不久前还没有开始编程,现在我需要一个方法来生成一个数组,其中包含一个位于前一个字符后面的字符。它应该在0处以"A"开头,然后在"1"处以"B"开头,等等。最困难的部分是使它在"Z"之后出现"AA"。

我想到了什么:

public static String[] charArray(int length)
{   
    String[] res = new String[length];
    for(int i = 0; i < length; i++)
    {
        String name = "";
        int colNumber = i;
        while(colNumber > 0)
        {
            char c = (char) ('A' + (colNumber % 26));
            name = c + name;
            colNumber = colNumber / 26;
        }
        res[i] = name;
    }
    return res;
}

这适用于字母表的前26个字母,但它会产生"…Y,Z,BA,BB,BC…"而不是"…Y、Z、AA、AB、AC…"

怎么了?或者有没有更有效或更简单的方法来做到这一点?

提前感谢!

您有一个良好的开端。这个例子基本上是根据数字%26 计算C的值,而不是运行while循环

然后,字母被添加(连接)到数组中位置为(index / 26) - 1的值,这确保了它能跟上随时间的变化。

当第一次迭代时,数组A B C等中的每个插槽中只有一个字母。

一旦你浏览了字母表,你就会有一个向后看的索引,并将当前字母添加到该值中。

你最终会进入AAA、AAB、AAC等,甚至更多。

    public static String[] colArray(int length) {   
    String[] result = new String[length];
    String colName = "";
    for(int i = 0; i < length; i++) {
        char c = (char)('A' + (i % 26));
        colName = c + "";
        if(i > 25){
            colName =  result[(i / 26) - 1] + "" + c;
        }
        result[i] = colName;
    }
    return result;
}

这样尝试:

public static String[] charArray(int length)
{   
    String[] res = new String[length];
    int counter = 0;
    for(int i = 0; counter < length; i++)
    {
        String name = "";
        int colNumber = i;
        while(colNumber > 0 && colNumber % 27 != 0)
        {  
            char c = (char) ('A' + ((colNumber) % 27) - 1);
            name = c + name;
            colNumber = colNumber / 27;
        }
        res[counter] = name;
        if (i % 27 != 0) {
            counter++;
        }
    }
    return res;
}

基本上,您的算法跳过了所有以A(A,AA,AB,…)开头的元素(因为当colNumber为0时会创建A,但这种情况永远不会发生,因为您的while在这种情况下终止)。取27的模,然后从char中减去1,就解决了这个问题。然后我们使用counter作为索引,否则我们将在数组中得到一些空元素(其中i将是i % 27 == 0)。

这个解决方案对我很有效。有26个词汇表字母,并且知道65是ASCII表中的字符"A",我们可以用这个递归方法获得增量。。。

private fun indexLetters(index: Int, prefix: String = "") : String {
    val indexSuffix:Int = index.rem(26)
    val suffix = (65 + indexSuffix).toChar().toString().plus(".")
    val newPrefix = suffix.plus(prefix)
    val indexPrefix: Int = index / 26
    return if (indexPrefix > 0) {
        indexLetters(indexPrefix - 1, newPrefix)
    } else {
        newPrefix
    }
}

你可以把这种kotlin方法称为

indexLetters(0) //To get an 'A'
indexLetters(25) //To get a 'Z'
indexLetters(26) //To get an 'A.A'
etcetera...

从数组迭代,取决于您的需求

最新更新