如何在C#中使用caesar密码中的for循环重复字母表

时间:2011-10-01 01:43:53

标签: c# for-loop encryption

我正在制作一个Caesar密码,我想在循环中制作字母,例如,如果字母'z'需要移位,它应该返回'a'表示大写和小写。

//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); 

如果我输入'xyz'并换一个,我会'yz{'

1 个答案:

答案 0 :(得分:1)

使用模运算:

new_pos = (current_pos + shift) % 26

current_pos必须是相对字母位置(例如:a=0, b=1... z=25)。类似的东西:

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';
}

参见工作演示:http://ideone.com/NPZbT


话虽如此,我希望这只是您正在玩的代码,而不是在实际代码中使用的代码。