В моем цикле метода Cypher у меня есть вложенный цикл, который фильтрует out символы, шифрование работает, но выдает ошибку
индекс вышел за пределы массива
При расшифровке я не совсем понимаю, почему? Кто-нибудь может помочь? Спасибо
Код: Выделить всё
static void Main(string[] args)
{
// get user message input
Console.Write("ENTER MESSAGE: ");
string messageIn = Console.ReadLine().ToLower();
// get modifier input and convert to int
Console.Write("MODIFIER?: ");
string modIn = Console.ReadLine();
int mod = Int32.Parse(modIn);
// convert message to an array of chars
char[] secretMessage = messageIn.ToCharArray();
// generate encryption and print
char[] encrypt = Crypt(secretMessage, mod);
string encryption = String.Join("", encrypt);
Console.WriteLine($"Encryption: {encryption}");
// generate decryption and print
char[] decrypt = Crypt(encrypt, -mod);
string decryption = String.Join("", decrypt);
Console.WriteLine($"Decryption: {decryption}");
}
static char[] Crypt(char[] input, int modi)
{
// vars
char[] alphabet = {'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'};
char[] symbs = {'!', '@', '#', '$', '%', ' '};
// make new empty array set to last arrays length
char[] cryptMesssageArray = new char[input.Length];
// for loop that loops through all cryptMessage chars
for (int i = 0; i < input.Length; i++)
{
bool flag = false;
// looping through symb to exclude them
foreach (char symb in symbs)
{
// checking if it uses a symb
if (input[i] == symb)
{
flag = true;
}
}
if (flag == true)
{
continue;
}
// vars
char secretChar = input[i];
int alphChar = (Array.IndexOf(alphabet, secretChar) + modi) % 26;
char cryptChar = alphabet[alphChar];
// add char to cryptMesssage
cryptMesssageArray[i] = cryptChar;
}
// return array
return cryptMesssageArray;
}
Код: Выделить всё
hello!
Я ожидаю
Код: Выделить всё
Encryption: khoor
Decryption: hello
Но вместо этого я получаю вот что:
Код: Выделить всё
Encryption: khoor
Подробнее здесь: https://stackoverflow.com/questions/781 ... run-a-nega