Mark Parfenov
Mark Parfenov

Reputation: 33

Remove blank lines from text file c#

Im trying to read a text file using File.ReadAllText, break it into single words and remove those unders certain length. But the thing is that blank lines or paragraphs are also count in a word length. Text example:

Just some simple text.

Here and there.

If we were to count words length it would look like this:

Blockquote

As you can see length of text. and Here became 13.

Here`s the code

var allLines =
            File.ReadAllText(filePath, Encoding.Default)
                .Split(' ')
                .Where(c => c.Length > wordLength)
                .Select(word => word);
        var newLine = string.Join(" ", allLines);   

Thanks in advance :)

Upvotes: 0

Views: 2559

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Combine the comment from SpaceghostAli, and the answer from Theofanis Pantelides:

        var allLines =
            File.ReadAllText(filePath, Encoding.Default)
            .Split(" \r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
            .Where(c => c.Length > wordLength);

Upvotes: 2

Theofanis Pantelides
Theofanis Pantelides

Reputation: 4854

Not very legible but you could String.Split with StringSplitOptions.RemoveEmptyEntries:

String allLines = string.Join(" ", File.ReadAllText(filePath, Encoding.Default)
                  .Split(new string[] { " ", "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries));

Upvotes: 3

Related Questions