Similar to previous answer but with the following suggestions
- Initialize longest and shortest.
- Ignore case when comparing. Could still do this with SequenceEqual instead of comparing strings. May not be needed if you know you won’t be comparing Anna to annA.
-
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); }
solved Write longest and shortest palindrome from text file