C# 读取包含由制表符分隔的数据的文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1028224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:53:33  来源:igfitidea点击:

C# Read Text File Containing Data Delimited By Tabs

c#text-filestabs

提问by Goober

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!?

任何人对如何解决这个问题有任何想法!?

采纳答案by Reed Copsey

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.

使用 String.Trim 应该可以很好地删除这些额外的字符。如果由于某种原因,对每个单词执行 String.Trim 不起作用,您需要切换以找出额外的“字符”是由什么组成的,并使用String.Trim 的这个重载

回答by Felipe Fujiy Pessoto

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

你有这样的空格/标签吗?“ 你好 ” ?

Trim remove white spaces and tabs too

修剪也删除空格和制表符