如何在C#中从文本文件中读取时删除空格? [英] How to remove blank spaces while reading from a text file in C#?

查看:100
本文介绍了如何在C#中从文本文件中读取时删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读包含逗号分隔值的文本文件。

文件中的内容如下:

ad,af ,,, EndofReport

我想只读取数据逗号分隔的内容。

ie:

ad,af,逗号分隔字符串中没有空值的EndofReport。



我尝试过:



核心代码如下:

I am reading a text file which contains comma separated values.
The content in the file will be as such:
ad,af,,,EndofReport
I want to read only the data with the comma separated contents.
ie:
ad,af,EndofReport without empty values in the comma separated string.

What I have tried:

Core Code as below:

string[] lines = System.IO.File.ReadAllLines(filePath);
                                    for (int j = 0; j < lines.Length; j++)
                                    {
                                      
                                        StdReportData = lines[j];
string[] words;
 words = StdReportData.Split(',');

}

推荐答案

你可以改变

You can change
words = StdReportData.Split(',');






to

words = StdReportData.Split(',',StringSplitOptions.RemoveEmptyEntries);





进一步阅读:String.Split方法(Char [],StringSplitOptions)(系统) [ ^ ]


最好的解决方案是不要 - CSV数据不仅仅是用逗号分隔,它还可以包含带引号的字符串,可以合法地包含逗号。



而不是在这里滚动你自己的解决方案,看看这个:快速CSV阅读器 [ ^ ] - 它为您完成了所有艰苦的工作!
The best solution is "don't" - CSV data isn't just "separated by comma" it can also contain quoted strings, which can legitimately contain commas.

Instead of "rolling your own" solution here, have a look at this: A Fast CSV Reader[^] - it does all the hard work for you!


请尝试以下方法:

Try as below:
string[] lines = System.IO.File.ReadAllLines(filePath);
            for (int j = 0; j < lines.Length; j++)
            {

                var StdReportData = lines[j];
                string[] words;
                words = StdReportData.Split(',')
                    .Select(x => x.Trim())
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .ToArray();

            }


这篇关于如何在C#中从文本文件中读取时删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆