Search code examples
c#cryptographycaesar-cipher

How to replace every different char with another given char


I need to replace every 'a' char with 'b' char, every 'b' char with 'c' char and so on. I've tried to make this with if but code is very very long for every char. Exists a method how mo make this without if or switch or something like that?

        char[] chars = new char[inputString.Length];
        for (int i = 0; i < inputString.Length; i++)
        {
            if (inputString[i] == 'a')
                chars[i] = 'b';
            else if (inputString[i] == 'b')
                chars[i] = 'c';
            else if (inputString[i] == 'c')
                chars[i] = 'd';
            else if (inputString[i] == 'd')
                chars[i] = 'e';
            else if (inputString[i] == 'e')
                chars[i] = 'f';
            else if (inputString[i] == 'f')
                chars[i] = 'g';
            else if (inputString[i] == 'g')
                chars[i] = 'h';
            else
            {
                chars[i] = inputString[i];
            }
        }
        string outputString = new string(chars);

This is how i need to replace:

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
Z 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

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
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 a


0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

Example: string: TEXTcsharp#2367 result: SDWSdtibsq#7632


Solution

  • You could cast it to int and add 1:

    char[] chars = new char[inputString.Length];
    for (int i = 0; i < inputString.Length; i++)
    {
        chars[i] = (char)(inputString[i] + 1);
    }
    string outputString = new string(chars);
    

    This works, because every char has a numeric representation. However you probably need some extra logic for z or so (depending if you want to constraint the values to the alphabet).

    Also since this is tagged with : Use Cryptography if you want to do encryption, instead of rolling your own. Even security experts have problems with creating a secure one.