Martin Martin - 5 months ago 29
C# Question

Increment an index that uses numbers and characters (aka Base36 numbers)

I have a string based code that can be either two or three characters in length and I am looking for some help in creating a function that will increment it.

Each 'digit' of the code has a value of 0 to 9 and A to Z.

some examples:

the first code in the sequence is 000

009 - next code is - 00A

00D - next code is - 00E

AAZ - next code is - AB0

the last code is ZZZ.

Hope this makes some sense.


Thanks for the advice guys.

This is what I independently came up with.

    private static String Increment(String s)
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        char lastChar = s[s.Length - 1];
        string fragment = s.Substring(0, s.Length - 1);

        if (chars.IndexOf(lastChar) < 35)
            lastChar = chars[chars.IndexOf(lastChar) + 1];

            return fragment + lastChar;

        return Increment(fragment) + '0';

I don't know if it is better/worse but seems to work. If anyone can suggest improvements then that is great.