I am trying to write a program what will write longest and shortest palindrome from words in text file. My code looks like this now:
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(@"C:\palindromy.txt");
foreach (string line in lines)
{
char[] charArray = line.ToCharArray();
for (int i = 0; i < 1; i++)
{
Array.Reverse(charArray);
bool a = charArray.SequenceEqual(line);
while(a == true)
{
Console.WriteLine(line); /that will just write all palindroms
break;
}
}
}
}
I am currently just writing all palindromes, but I need to write just longest and shortest one.
Similar to previous answer but with the following suggestions
When checking if you found the shortest you need to remember that shortest.Length with be 0 to start so you will want to store the first palindrome found in shortest if shortest.Length==0.
static void Main(string[] args)
{
var lines = System.IO.File.ReadAllLines(@"C:\palindromy.txt");
string longest = string.Empty;
string shortest = string.Empty;
foreach (var line in lines)
{
if (line.Length == 0) continue;
char[] charArray = line.ToCharArray();
Array.Reverse(charArray);
string reversedLine = new string(charArray);
if (line.Equals(reversedLine, StringComparison.OrdinalIgnoreCase))
{
if (line.Length > longest.Length)
{
longest = line;
}
if (line.Length < shortest.Length || shortest.Length == 0)
{
shortest = line;
}
}
}
Console.WriteLine(longest);
Console.WriteLine(shortest);
}