Monday, July 9, 2012

c# - Longest string in a file

The below code can be modified for other csv files easily.
If the data in the file is delimited by characters other than tab then replace '\t' in the sLine split function below

int iMaxLength = 0;
using (StreamWriter writer = new StreamWriter(ConfigurationSettings.AppSettings["OUTPUT_FILE_NAME"]))
{
    using (StreamReader reader = new StreamReader(ConfigurationSettings.AppSettings["INPUT_FILE_NAME"]))
    {
         while (!reader.EndOfStream)
         {
              String sLine = reader.ReadLine();
              String[] sLineItem = sLine.Split('\t');
              foreach (String item in sLineItem)
              {
                    if (item.Length > iMaxLength)
                    {
                          iMaxLength = item.Length;
                          Console.WriteLine("Item:" + item + " Length:" + item.Length);
                          writer.WriteLine("Item:" + item + " Length:" + item.Length);
                    }
              }
         }
         Console.WriteLine("Final Max Length:" + iMaxLength.ToString());
         writer.WriteLine("Final Max Length:" + iMaxLength.ToString());
    }
}
Console.Read();

No comments: