user1191027
user1191027

Reputation:

Increment Alphabet Characters By Numeric Value

I need a java method that takes in an integer and then increments it and gives you the respective alpha character. Something like this:

public String getAlpha(Integer number) {
   ...
}

So if I pass the number value equal 0 then it should increment and return the letter a. If I pass it 25 then it should return the letter z. If I pass it the number 26 then it should return aa. If I pass it the number 27 then it should return ab and so on.

The alpha's pretty much simulate the way excel sheet columns are represented, all I need to do is get the alpha value from a method by passing it a number. There is no set limit except the String that gets returned from getAlpha must be a maximum of 15 chars and a minimum of 1 char.

Upvotes: 0

Views: 1223

Answers (3)

mokshino
mokshino

Reputation: 1493

it is the same the Excel column naming:

public class Calculator {

    private static String[] letters = new String[]{
        "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 void main(String[] args) {
        System.out.println(calculate(731));
    }

    public static String calculate(int row) {
        return calculateRecursive(row - 1, "");
    }

    private static String calculateRecursive(int row, String res) {
        String val = letters[row % letters.length] + res;
        int i = row / letters.length;
        if(row >= letters.length) {
            return calculateRecursive(i - 1, val);
        }
        return val;

    }
}

Upvotes: 0

Sednus
Sednus

Reputation: 2113

I believe this will do what you want, I don't know if it can be done more efficiently:

static void printCode(int code) {
  final StringBuilder buffer = new StringBuilder();
  do {
    final int digit = (code - 1) % 26;
    buffer.insert(0, (char)(digit + 'a'));
    code = (code - digit - 1) / 26;
  } while (code > 0);
  System.out.println(buffer);
}

Upvotes: 0

jolivier
jolivier

Reputation: 7655

This is how you generate a - z from numbers between 0 and 25 in Java:

protected static String getLetter(int code) {
    if (code >= 0 && code <= 25)
        return "" + (char) (code  + 'a');
    else
        throw new IllegalArgumentException("char code is out of bound: " + code);
}

the rest is just modulo Math.

Upvotes: 1

Related Questions