开发者

How to repeat the alphabet with for loop in caesar cipher in C#

I am making a Caesar cipher and I want to make the letters in a loop so for example if the letter 'z' needs to be shifted it should go back to 'a' for both capital and lowercase.

//Array that holds each char in the plaintext inputed is declared and initiated
char[] chars = plainTextInput.ToCharArray();

//For loop that will go through each letter and change the value of each letter by adding the shiftAmount
for (int i = 0; i < plainTextInput.Length; ++i)
{   
    chars[i] = (char)(((int)chars[i]) + shiftAmount);

    if (chars[i] >= 97 && chars[i] <= 122)
    {
        if (chars[i] > 122)
        {
            int x = chars[i] - 123;
            chars[i] = (char)((int)(97 + x));
        }
    }
}  

//Variable for ciphertext output holds char array chars as a string
cipherTextOutput = new string(chars); 

If I input 'xyz' and shift by开发者_JS百科 one I get 'yz{'.


Use modulo arithmetic:

new_pos = (current_pos + shift) % 26

current_pos has to be the relative letter position (eg: a=0, b=1... z=25). Something like:

if ('A' <= c && c <= 'Z')      // uppercase
{
    current_pos = (int) c - (int) 'A';
}
else if ('a' <= c && c <= 'z') // lowercase
{
    current_pos = (int) c - (int) 'a';
}

See working demo: http://ideone.com/NPZbT


That being said, I hope this is just code you are playing with, and not something to be used in real code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜