В настоящее время я пишу программу Cesar Cipher для C# для моего задания, и у меня возникла проблема.Caesar Cipher Shift (с использованием набора символов)
Я подхожу к этой задаче, используя массив, в котором храню весь алфавит, и объявляю переменную сдвига, которая определяется символьным индексом в массиве - итерацией цикла for. Расчет сдвига выполняется в цикле foreach, который извлекает символ из строки, которая считывается из текстового файла. Цикл Foreach содержится в цикле for, который выполняет итерацию для вывода каждого возможного сдвига.
Однако проблема заключается в том, что когда я пытаюсь получить доступ к символу в массиве по значению переменной shift, программа, похоже, не имеет доступа к символу, который я хочу, он просто выводит тот же символ, что и в оригинальная строка.
Это код программы:
using System;
using System.IO;
public class caesar_shift
{
public static void Main()
{
string file = @"C:\Users\terasss2\Desktop\Programming and Data Structures\caesarShiftEncodedText.txt"; //String variable that stores a file location
string encrypted_text = File.ReadAllText(file); //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
char[] alphabet = new char[26]{'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'};
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for(int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
foreach(char c in encrypted_text)
{
character = c;
if(character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if(shift <= 0)
shift = shift + 26;
if(shift >= 26)
shift = shift - 26;
character = alphabet[shift]; //Set the character to a shifted letter by accessing the array element of a value shift
Console.WriteLine(character);
decoded_text = decoded_text + character;
}
Console.WriteLine("\nShift {0} \n {1}",i + 1, decoded_text);
}
}
}
Единственная проблема заключается в том, что буквы в текстовом файле все в верхнем регистре – terasss2
просто преобразуют ваш зашифрованный текст в нижний регистр. Используйте этот ToLowerInvariant() –