trim all strings in an array

Viewed 80946

I have a string that comes in like:

string email = "a@a.com, b@b.com, c@c.com";

I want to split it into an array of strings

If I do this:

string[] emails = email.Split(',');

I get spaces in front of each email address (after the first one):

emails[0] = "a@a.com"
emails[1] = " b@b.com"
emails[2] = " c@c.com"

What is the best way to get this (either a better way to parse or a way to trim all strings in an array)?

emails[0] = "a@a.com"
emails[1] = "b@b.com"
emails[2] = "c@c.com"
12 Answers

You can use a one line solution like this:

string[] emails = text.Split(',', StringSplitOptions.RemoveEmptyEntries);
Array.ForEach<string>(emails, x => emails[Array.IndexOf<string>(emails, x)] = x.Trim());

.NET 5 has arrived and with it, a modern solution to this problem:

string[] emails = email.Split(',', StringSplitOptions.TrimEntries);

If you just need to manipulate the entries, without returning the array:

string[] emails = text.Split(',');
Array.ForEach(emails, e => e.Trim());

In .NET 5, they added StringSplitOptions.TrimEntries.

You can use it like

string[] emails = email.Split(',', StringSplitOptions.TrimEntries);

Which will give you

emails[0] = "a@a.com"
emails[1] = "b@b.com"
emails[2] = "c@c.com"
Related