Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Read Text File Containing Data Delimited By Tabs

I have some code:

 public static void ReadTextFile()
    {
        string line;

        // Read the file and display it line by line.
        using (StreamReader file = new StreamReader(@"C:\Documents and Settings\Administrator\Desktop\snpprivatesellerlist.txt"))
        {
            while ((line = file.ReadLine()) != null)
            {

                char[] delimiters = new char[] { '\t' };
                string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < parts.Length; i++)
                {

                     Console.WriteLine(parts[i]);
                     sepList.Add(parts[i]);

                }

            }

            file.Close();
        }
        // Suspend the screen.
        Console.ReadLine();     
    }

It reads in a text file that contains data delimited by tabs and splits the data into separate words.

The problem I have is that once the data has been separated, it still has massive amounts of white space on the left and right sides on random strings in the list (Infact most of them do). I can't trim the string because it only removes white space, and technically this isn't white space.

Anyone got any ideas on how to get round this problem!?

like image 625
Goober Avatar asked Jun 22 '09 16:06

Goober


2 Answers

The problem I have is that once the data has been separated, it still has massive amounts of white space on the left and right sides on random strings in the list (Infact most of them do). I can't trim the string because it only removes white space, and technically this isn't white space.

It sounds like you have non-tab whitespace characters in your string, as well as being tab delimited.

Using String.Trim should work fine to remove these extra characters. If, for some reason, doing String.Trim on each word is not working, you'll need to switch to find out what the extra "characters" are comprised of, and using this overload of String.Trim.

like image 142
Reed Copsey Avatar answered Oct 20 '22 00:10

Reed Copsey


You have white space/tabs like this? "    Hello " ?

Trim remove white spaces and tabs too

like image 34
Felipe Pessoto Avatar answered Oct 19 '22 23:10

Felipe Pessoto