该程序已成功使用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.");
}
一种方法是创建一个变量,如果在true
数组中找到该字符,则将其设置为alphabet
。然后,在内循环之后,我们知道如果找不到该字符,则它是一个“特殊字符”或一个数字,我们可以将其添加。
例如:
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;
}
}