如何在c#凯撒密码中使用for循环重复字母表
本文关键字:for 循环 字母表 凯撒 密码 | 更新日期: 2023-09-27 18:10:06
我正在制作凯撒密码,我想让字母在一个循环中,例如,如果字母'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'
并移动1,我得到'yz{'
使用模运算:
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
话虽这么说,我希望这只是你正在玩的代码,而不是在实际代码中使用的东西。