Martin Martin - 1 year ago 73
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download