Perform Trim() while using Split()

Another possible option (that avoids LINQ, for better or worse):

string line = " abc, foo  ,     bar";
string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim());

However, if you just need to know if it is there - perhaps short-circuit?

bool contains = line.Split(',').Any(p => p.Trim() == match);

I know this is 10 years too late but you could have just split by ' ' as well:

string[] split= keyword.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);

Because you're also splitting by the space char AND instructing the split to remove the empty entries, you'll have what you need.


var parts = line
    .Split(';')
    .Select(p => p.Trim())
    .Where(p => !string.IsNullOrWhiteSpace(p))
    .ToArray();

If spaces just surrounds the words in the comma separated string this will work:

var keyword = " abc, foo  ,     bar";
var array = keyword.Replace(" ", "").Split(',');
if (array.Contains("foo"))
{
    Debug.Print("Match");
}

Tags:

C#

String

Trim