Friday, July 16, 2010

Loading a 2 Column Text File into Lists - C#

I came across a text file that is split into two columns, with each column split up by spaces or tabs. This method loads the text file into two different lists of strings.

Note: In this case, the columns are split up by at least 2 spaces.
Note2: The method is part of a bigger class that has the following variables:
List src = new List();
List trg = new List();
//loads a text file dictionary where both segments are on the same line and are seperated by multiple spaces
        //ex. "a specified period of time         eine genau bestimmte Frist"
        public void loadDictionary(FileInfo file)
        {
            fileName = file.Name.Substring(0, file.Name.Length - 4) + "_" + timeHolder + ".tmx"; //taking off extension

            Console.WriteLine("Loading language segments from dictionary {0}.", file.Name);
            StreamReader sr = new StreamReader(file.FullName);

            string line;

            while ((line = sr.ReadLine()) != null)
            {
                char[] chars = line.ToCharArray();
                int spaces = 0;
                int index = 0;

                foreach (char c in chars)
                {
                    if (c.Equals(' '))
                        spaces++;
                    else //not out of word
                        spaces = 0;


                    if (spaces >= 2) //if its a break between words
                    {
                        src.Add(lineIteg(line.Substring(0, index).Trim()));
                        trg.Add(lineIteg(line.Substring(index, line.Length - index).Trim()));
                        break;
                    }
                    index++;
                }
            }
            sr.Close();
        }

0 comments:

Post a Comment