Incrementing charaters past 'Z' in Java like a Spreadsheet

Viewed 2397

I didn't start too long ago with programming, and currently I need a method to produce an array, containing a character which is comes after the previous character. It should start with an 'A' at 0, then a B at '1' etc.. The hard part is making it so that after the 'Z' comes 'AA'.

What I came up with:

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;
}

This works fine for the first 26 letters of the alphabet, but it produces "... Y, Z, BA, BB, BC..." instead of "... Y, Z, AA, AB, AC..."

What's wrong? Or are there any more efficient or easier ways to do this?

Thanks in advance!

3 Answers

This solution works for me. Having 26 vocabulary letters and knowing that 65 is the char 'A' in ASCII table, we can get the incrementing with this recursive method...

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
    }
}

You can call this kotlin method like

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

from an array iteration, depending of your requirements

Related