简体   繁体   中英

How to exchange numbers to alphabet and alphabet to numbers in a string?

How do I convert numbers to its equivalent alphabet character and convert alphabet character to its numeric values from a string (except 0, 0 should stay 0 for obvious reasons)

So basically if there is a string

string content="D93AK0F5I";

How can I convert it to ?

string new_content="4IC11106E9";

I'm assuming you're aware this is not reversible, and that you're only using upper case and digits. Here you go...

    private string Transpose(string input)
    {
        StringBuilder result = new StringBuilder();
        foreach (var character in input)
        {
            if (character == '0')
            {
                result.Append(character);
            }
            else if (character >= '1' && character <= '9')
            {
                int offset = character - '1';
                char replacement = (char)('A' + offset);
                result.Append(replacement);
            }
            else if (character >= 'A' && character <= 'Z') // I'm assuming upper case only; feel free to duplicate for lower case
            {
                int offset = character - 'A' + 1;
                result.Append(offset);
            }
            else
            {
                throw new ApplicationException($"Unexpected character: {character}");
            }
        }

        return result.ToString();
    }

Well, if you are only going to need a one way translation, here is quite a simple way to do it, using linq:

string convert(string input)
    {
        var chars = "0abcdefghijklmnopqrstuvwxyz";
        return string.Join("", 
                           input.Select(
                               c => char.IsDigit(c) ? 
                               chars[int.Parse(c.ToString())].ToString() : 
                               (chars.IndexOf(char.ToLowerInvariant(c))).ToString())
                           );
    }

You can see a live demo on rextester.

You can use ArrayList of Albhabets. For example

ArrayList albhabets = new ArrayList();
            albhabets.Add("A");
            albhabets.Add("B");

and so on.

And now parse your string character by character.

string s = "1BC34D";
char[] characters = s.ToCharArray();
for (int i = 0; i < characters.Length; i++)
 {
   if (Char.IsNumber(characters[0]))
    {
        var index = characters[0];
        var stringAlbhabet = albhabets[index];
    }
  else
    {
        var digitCharacter = albhabets.IndexOf(characters[0]);
    }
}

This way you can get "Alphabet" representation of number & numeric representation of "Alphabet".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM