用我自己的语言向字符串添加操作

add operation to string in my own language

我有一个 5 个字符的单词,例如:

"AD5B6" , "1G2H0" , "HASAN" , "ABC5Z" , "1ZZZZ"

我在单词中添加“1”时需要新值(例如计数系统),因此结果如下:

"AD5B7" , "1G2H1" , "HASAO" , "ABC60" , "20000"

我为此编写了代码,但我在 'Z' 字符中遇到了问题,因为我需要增加以前的值。 我的 C# 代码是:

public string Get(string h)
{
    var lang = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string hash = h.ToUpper();
    char c = hash[hash.Length - 1]; // last char in the word
    string result = "";
    for (int i = 0; i < lang.Length; i++)
    {
        if (c == lang[i] && c != 'Z')
        {
            char cc = lang[i + 1];   // last char + 1
            string s1 = hash.Split(c)[0];
            string s2 = hash.Split(c)[1];
            result = s1 + cc + s2;
            break;
        }
        else
        { // the wrong in this code and i think i should do it in recursive way
            char cc = '0';
            string s1 = hash.Split(c)[0];
            char s11 = s1[s1.Length - 1];
            string s2 = hash.Split(c)[1];
            result = s1 + cc + s2;
            break;
        }
    }
    return result;
}

您似乎想执行 Base36 操作,例如

var base36 = new BaseN("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");

Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("AD5B7") + 1) );
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("1ZZZZ") + 1) );
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("ZZZZZ") + 1));
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("6ZZZZZZZZZZZZZZZZZZ") + 1) );

Console.WriteLine(base36.ToBaseNString(base36.FromBaseNString("123") * 2));

任何字符集的通用算法都可以写成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

public class BaseN
{
    List<char> CHARSET = null;

    public BaseN(string charset)
    {
        CHARSET = new List<char>(charset);
    }

    public String ToBaseNString(BigInteger input)
    {
        var stack = new Stack<char>();
        while (input != 0)
        {
            stack.Push(CHARSET[(int)(input % CHARSET.Count)]);
            input /= CHARSET.Count;
        }
        return new string(stack.ToArray());
    }

    public BigInteger FromBaseNString(string input)
    {
        BigInteger sum = 0;
        int i = 0;
        foreach (char c in input.Reverse())
        {
            sum += CHARSET.IndexOf(c) * BigInteger.Pow(CHARSET.Count, i++);
        }
        return sum;
    }
}

尽管在 C# 中有更好的按位运算方法,您也可以这样做:

var base2 = new BaseN("01");
Console.WriteLine( base2.ToBaseNString(base2.FromBaseNString("11") *3 ) );