Reputation: 3705
I have a string which I would like to split on a particular delimiter and then remove starting and trailing whitespace from each member. Currently the code looks like:
string s = "A, B, C ,D";
string[] parts = s.Split(',');
for(int i = 0; i++; i< parts.Length)
{
parts[i] = parts[i].Trim();
}
I feel like there should be a way to do this with lambdas, so that it could fit on one line, but I can't wrap my head around it. I'd rather stay away from LINQ, but I'm not against it as a solution either.
string s = "A, B, C ,D";
string[] parts = s.Split(','); // This line should be able to perform the trims as well
I've been working in Python recently and I think that's what has made me revisit how I think about solutions to problems in C#.
Upvotes: 1
Views: 244
Reputation: 28338
If you really want to avoid LINQ, you can split on multiple characters and discard the extra "empty" entries you get between the "," and spaces. Note that you can end up getting odd results (e.g. if you have consecutive "," delimiters you won't get the empty string in between them anymore):
s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
This will work for your sample input, but its very fragile. For example, as @Oscar points out, whitespace inside your tokens will cause them to get split as well. I'd highly recommend you go with one of the LINQ-based options instead.
Upvotes: 1
Reputation: 29863
What about:
string[] parts = s.Split(',').Select(x => x.Trim()).ToArray();
Upvotes: 8