0

I have a method I am trying to test

    public static string BySpace(string s, int position)
    {
        return s.Split()[position];
    }

I have a test function around it

    [Theory]
    [InlineData("a  b   c   d")]
    [InlineData(" a  b   c   d")]
    [InlineData("a  b   c   d ")]
    [InlineData("a b c d")]
    [InlineData(" a b c d ")]
    public void TestParseToList(string s)
    {
        Assert.Equal("a", Util.BySpace(s, 0));
        Assert.Equal("b", Util.BySpace(s, 1));
        Assert.Equal("c", Util.BySpace(s, 2));
        Assert.Equal("d", Util.BySpace(s, 3));
    }

A bunch of inline data tests fail. As can be seen i am playing with Space & Tab.

Desired effect: Take a string and split it by any white space

What am i missing please? How can I take a string and split it by space

I tried all of the below to no avail

// return s.Split()[position];
// return s.Split(' ')[position];
// return s.Split("\\s+")[position];  <----- i had high hopes for this one
// return s.Split(null)[position];
// return s.Split(new char[0])[position];
creturn s.Split(new char[0], StringSplitOptions.RemoveEmptyEntries)[position]);
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

2 Answers2

2

When you call Split you can pass multiple chars that you want to split on:

return s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)[position];

In this case you have spaces ' ' and tabs '\t'

Simply Ged
  • 8,250
  • 11
  • 32
  • 40
2

The following will resolve your issue:

//avoid null reference exception
if(!string.IsNullOrEmpty(s))
{
   //remove any whitespace to the left and right of the string
   s = s.Trim();
   // Here we use a regular expression, \s+
   // This means split on any occurrence of one or more consecutive whitespaces.
   // String.Split does not contain an overload that allows you to use regular expressions
   return System.Text.RegularExpressions.Regex.Split(s, "\\s+")[position];
}
else { return null; }
Byron Jones
  • 702
  • 5
  • 11