Search code examples
c#arraysstringtrim

Getting an extra entry in array for each newline


For the following code...

IEnumerable<string> items=searchterms.Trim().Split(Environment.NewLine.ToCharArray());
foreach (var item in items) {

I'm getting an item of length 0 in-between each searchterm item. I've used similar code elsewhere and not run into this, so not sure why it's happenning now. What do I need to add here to get rid of these extra entries? i.e. so that the number of items matches the number of terms in the input. I have a work-around (skip items with length 0), but it's an annoyance that the numbers don't match, and I would like to fix it for displaying progress purposes. i.e. item i+1 of items.count.

P.S. this is in Xamarin Forms on UWP.

thanks, Donald.


Solution

  • Since the newline is composed from 2 characters (on most systems anyway, \r and \n), you may be getting an extra empty string as the string between these characters.

    Try this:

    IEnumerable<string> items=searchterms.Trim().Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
    foreach (var item in items) {