Increase the index that uses numbers and characters (also called Base36 numbers)

I have a string code that can contain two or three characters, and I'm looking for some help in creating a function that will increase it.

Each "digit" of the code has values ​​from 0 to 9 and from A to Z.

a few examples:

first code in sequence 000

009 - next code - 00A
00D - next code - 00E AAZ
- next code - AB0

The last code is ZZZ.

Hope this makes sense.

+3
source share
3 answers

Thanks for the advice guys.

This is what I myself 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 do not know whether it is better or worse, but it seems to work. If someone can suggest improvements, that's great.

+2
source

int . int 36 . (0-35) 0-Z.

, :

internal class Program
{
    const int Base = 36;

    public static void Main()
    {
        Console.WriteLine(ToInt("0AA"));
        Console.WriteLine(ToString(370));
    }

    private static string ToString(int counter)
    {
        List<char> chars = new List<char>();

        do
        {
            int c = (counter % Base);

            char ascii = (char)(c + (c < 10 ? 48 : 55));

            chars.Add(ascii);
        }
        while ((counter /= Base) != 0);

        chars.Reverse();

        string charCounter = new string(chars.ToArray()).PadLeft(3, '0');

        return charCounter;
    }

    private static int ToInt(string charCounter)
    {
        var chars = charCounter.ToCharArray();

        int counter = 0;

        for (int i = (chars.Length - 1), j = 0; i >= 0; i--, j++)
        {
            int chr = chars[i];

            int value = (chr - (chr > 57 ? 55 : 48)) * (int)Math.Pow(Base, j);

            counter += value;
        }

        return counter;
    }

. 10 .NET?.

+3

Does it do what you need?

public class LetterCounter
{
    private static readonly string[] _charactersByIndex = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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 string GetStr(int i)
    {
        if (i < _charactersByIndex.Length)
            return _charactersByIndex[i];

        int x = i / (_charactersByIndex.Length - 1) - 1;
        string a = _charactersByIndex[x];
        string b = GetStr(i - (_charactersByIndex.Length - 1));
        return a + b;
    }
}

}

+1
source

Source: https://habr.com/ru/post/1783261/


All Articles