Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringSplitOptions.RemoveEmptyEntries doesn't work as advertised

I've come across this several times in the past and have finally decided to find out why.

StringSplitOptions.RemoveEmptyEntries would suggest that it removes empty entries.

So why does this test fail?

var tags = "One, Two, , Three,   Foo Bar, , Day    , ";  var tagsSplit = tags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)     .Select(s => s.Trim());  tagsSplit.ShouldEqual(new string[] {     "One",     "Two",     "Three",     "Foo Bar",     "Day" }); 

The result:

  Values differ at index [2]   Expected string length 5 but was 0. Strings differ at index 0.   Expected: "Three"   But was:  <string.Empty> 

So it fails because instead of "Three", we have an empty string – exactly what StringSplitOptions.RemoveEmptyEntries should prevent.

like image 508
Ben Foster Avatar asked May 21 '12 09:05

Ben Foster


1 Answers

Most likely because you change the string after the split. You trim the values after splitting them, RemoveEmptyEntries doesn't consider the string " " empty.

The following would achieve what you want, basically creating your own strip empty elements:

var tagsSplit = tags.Split(',').                   Select(tag => tag.Trim()).                    Where( tag => !string.IsNullOrEmpty(tag)); 
like image 148
TJHeuvel Avatar answered Sep 20 '22 09:09

TJHeuvel