该程序成功地使用了ROT-13算法,但它没有捕获任何特殊字符或数字,相反,特殊字符和数字根本没有保存在输出文件中。对于要输出的数字和特殊字符,我需要对代码进行哪些更改?
static void Encode ()
{
string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // declaring alphabet
string strROT13 = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"; // declaring alphabet using the ROT13 system
Console.WriteLine("Enter the name of the file you would like to encode (.txt, .bat, etc): "); // prompts user to read in file
string inputFile = Console.ReadLine();
if (!File.Exists(inputFile)) { // test to see if file is found
Console.WriteLine("File not found, please try again.");
return;
}
Console.WriteLine("Enter the name of the file you would like to save to (.txt, .bat, etc): "); // asks user where to save translated file
string outputFile = Console.ReadLine();
StreamReader input = new StreamReader(inputFile); // reads file
StreamWriter output = new StreamWriter(outputFile); // writes file
string str = ""; // reading file line by line
while ((str = input.ReadLine()) != null) // reads entire file
{
string encoded = "";
int length = str.Length;
if (length > 0)
{
foreach (char character in str) // takes each character from the line
{
if (character == ' ') // if a space in file, left unchanged
encoded += ' ';
else
for (int i = 0; i < 52; i++) // if character in array, then encoded
if (character == alphabet[i])
encoded += strROT13[i];
}
}
output.WriteLine(encoded); // writes encoded string to the new file
}
input.Close();
output.Close();
Console.WriteLine("The file was successfully encoded.");
}
实现这一点的一种方法是创建一个变量,如果在alphabet
数组中找到字符,则将该变量设置为true
。然后,在内部循环之后,我们知道如果没有找到字符,它就是一个"特殊字符"或数字,我们可以添加它。
例如:
foreach (char character in str) // takes each character from the line
{
bool characterFound = false;
for (int i = 0; i < alphabet.Length; i++) // if character in array, then encoded
{
if (character == alphabet[i])
{
encoded += strROT13[i]; // add the encoded character
characterFound = true; // set our variable to indicate it was found
break; // break out of the for loop early
} // since there's no need to keep searching
}
// If this character was not found in alphabet, just add it as-is
if (!characterFound)
{
encoded += character;
}
}
我认为您应该对字符串中未包含的所有字符进行常规检查,然后手动将它们附加到编码的字符串中。试试这个:
foreach (char character in str) // takes each character from the line
{
if (alphabet.ToCharArray().Contains(character))
{
encoded += strROT13[Array.IndexOf(alphabet.ToCharArray(), character)];
}
else
{
encoded += character;
}
}