Search code examples
c#arraysstringtext-filespalindrome

Write longest and shortest palindrome from text file


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.


Solution

  • Similar to previous answer but with the following suggestions

    1. Initialize longest and shortest.
    2. 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.
    3. 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);
      }