简体   繁体   English

拆分long String In C# 到Array,返回第一个元素为空?

[英]Split long String In C# to Array, return first element empty?

I have a log file with some lines:我有一个包含几行的日志文件:

test123 (random text..)
test123 (random text..)
test123 (random text..)

I want to convert it into an array, so I did the following:我想把它转换成一个数组,所以我做了以下事情:

string[] myArray = logFileText.Replace("test123", "#test123").Split("#");

This work fine except for the fact that the first element in myArray is empty.. any idea how to solve this?这工作正常,除了 myArray 中的第一个元素是空的。知道如何解决这个问题吗?

Note: cannot use Environment.NewLine, it does not work on this file for some reason..注意:不能使用 Environment.NewLine,由于某种原因它不适用于此文件。

As @pm100 said, this is the answer:正如@pm100所说,这就是答案:

Split('#', StringSplitOptions.RemoveEmptyEntries)

You could add a .Skip(1) to the end of your code:您可以在代码末尾添加.Skip(1)

string[] myArray = logFileText.Replace("test123", "#test123").Split("#").Skip(1).ToArray();

You need to read the file line-by-line.您需要逐行阅读文件。 This should work这应该工作

  var filePath = "D:\\MyLogfile.txt";

        var fileContents = File.ReadAllLines(filePath); //Reads line by line
        if (fileContents.Length > 0) //If file has any lines/content
        {
            var myFileContents = fileContents.Skip(1); //Skips the first row

            foreach (var fileLine in myFileContents) //Process line by line
            {
                
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM