Reputation: 13
I'm trying to get a string array with single words from a textfile. However the array is filled with some empty lines. Any Idea how I can make a string array without those empty lines?
WebClient client = new WebClient();
Stream stream = client.OpenRead("https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt");
StreamReader reader = new StreamReader(stream);
string[] content = reader.ReadToEnd().Split('?', '!', ' ', '\n', '[', ']', '.');
for (int i = 0; i < 5; i++)
{
Console.WriteLine(content[i]);
}
Console.ReadLine();
Upvotes: 0
Views: 3486
Reputation: 26635
You can try Split()
method overload which takes StringSplitOptions
as a second parameter with the value RemoveEmptyEntries
. Then the return value does not include array elements that contain an empty string.
var result = reader.ReadToEnd()
.Split(new[] {'?', '!', ' ', '\n', '[', ']', '.'} , StringSplitOptions.RemoveEmptyEntries);
By the way, after this you can call Trim()
for all elements, because RemoveEmptyEntries
doesn't consider the string " "
empty. So you can add this to your code, if you want to discard empty strings:
var result = reader.ReadToEnd()
.Split(new[] {'?', '!', ' ', '\n', '[', ']', '.'} , StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x.Trim())
.ToArray();
Upvotes: 6
Reputation: 54781
As you are calling Split
, you can do it with the options as detailed in other answer. If you were not however and wanted to remove empty lines from an array using linq:
content = content.Where(s => s != "").ToArray();
Upvotes: 0