83

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"
1
  • 2
    If the space will always be there, you could add it to the split... ie: email.Split(', ');
    – nilamo
    Aug 31, 2009 at 4:02

12 Answers 12

263
emails.Split(',').Select(email => email.Trim()).ToArray()
11
  • 3
    @Moismyname: I'm not sure what constraint would lead you down that path, but there are other answers that address your question. May 14, 2015 at 18:55
  • Nice and clean. Worked perfectly for me. Thanks!
    – KidBilly
    Aug 20, 2015 at 17:12
  • 10
    This is better than the accepted answer, as the question was to TRIM each string, not necessarily replace spaces with blanks.
    – daveD
    Apr 13, 2017 at 13:10
  • 1
    @IrfanUllah: Chain a .Where(email => email != null) Jun 21, 2017 at 15:25
  • 1
    @MinhTran It is indeed a function call - Select is a family of extension methods that make up LINQ in the System.Linq namespace. Oct 12, 2018 at 14:32
41

You could also replace all occurrences of spaces, and so avoid the foreach loop:

string email = "a@a.com, b@b.com, c@c.com";    
string[] emails = email.Replace(" ", "").Split(',');
5
  • 13
    Works ok for this specific example, but doesn't maintain spaces for the resultant elements like; "foo bar, another element, blah_blah". Bryan Watts has the best answer IMO.
    – revgum
    Jun 11, 2012 at 14:33
  • 1
    Hi @revgum! That's true, but I have sticked to comply @leora's requirements. The example you´re describing, IMO, is outside the context of this question. Thanks anyway for your feedback.
    – nick2083
    Jun 27, 2012 at 0:29
  • 2
    -1 I agree that this is not a good thing to do. Buyer beware. Jun 19, 2013 at 13:04
  • also downvoted. i agree that the answer does the trick, but Bryans answer is more useful in general Feb 12, 2014 at 10:36
  • This isn't right. It will not trim, but remove spaces from strings in array, which is totally different from trim (removing trailing and leading spaces)
    – SimpleGuy
    Nov 13, 2020 at 2:24
23

Either one of the following would work. I'd recommend the first since it more accurately expresses the joining string.

string[] emails = email.Split(new string[] { ", " }, StringSplitOptions.None);
string[] emails = email.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
3
  • +1 I didn't know about the options. Coming from Perl I see regexs everywhere. With the options Split is the way to go. Aug 31, 2009 at 4:19
  • 2
    +1 we use LINQ so much that we tend to forget that other elegant options do exist.
    – Stan R.
    Aug 31, 2009 at 4:39
  • In this specific case, email addresses can't have spaces, so I would use the second option.
    – Moses
    Oct 10, 2022 at 17:59
11

You can use Trim():

string email = "a@a.com, b@b.com, c@c.com";
string[] emails = email.Split(',');
emails = (from e in emails
          select e.Trim()).ToArray();
1
8

Use Regex.Split to avoid trimming

var emails = Regex.Split(email, @",\s*");
6

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

string[] emails = email.Split(',', StringSplitOptions.TrimEntries);
1
  • This should be considered as the best option, as it's more perf than any other answer here
    – cdie
    Oct 13, 2021 at 13:55
5

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());
0
4

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

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

Alternatively, you can split using a regular expression of the form:

\s*,\s*

i.e.

string[] emails = Regex.Split(email, @"\s*,\s*");

It will consume the surrounding spaces directly.

Regular expressions are usually a performance hit, but the example you gave indicates that this is something you plan to do once in your code for a short array.

1

The answer from Bryan Watts is elegant and simple. He implicitly refers to the array of strings created by the Split().

Also note its extensibility if you are reading a file, and want to massage the data while building an array.

string sFileA = @"C:\Documents and Settings\FileA.txt";
string sFileB = @"C:\Documents and Settings\FileB.txt";

// Trim extraneous spaces from the first file's data
string[] fileAData = (from line in File.ReadAllLines( sFileA )
                      select line.Trim()).ToArray();

// Strip a second unneeded column from the second file's data
string[] fileBData = (from line in File.ReadAllLines( sFileB )
                      select line.Substring( 0, 21 ).Trim()).ToArray();

Of course, you can use the Linq => notation if you prefer.

string[] fileBData = File.ReadAllLines( sFileB ).Select( line =>
                             line.Substring( 0, 21 ).Trim()).ToArray();

Although my answer should have been posted as a comment, I don't have enough reputation points to comment yet. But I found this discussion invaluable in figuring out how to massage data while using ReadAllLines().

2
  • Wecome to Stack Overflow. One small point on your code: If you're using Linq like that, you might be better using File.ReadLines. ReadAllLines "slurps" the entire file into an array in memory, which can obviously be problematic with big files. ReadLines only reads one line at a time, which is great if you don't need to keep the initial version of the contents.
    – RoadieRich
    Mar 17, 2016 at 21:02
  • Thanks! I can see that the example using ReadAllLines will break down for very large files, containing both the raw data and the trimmed versions in memory at the same time, for a moment. The documentation page for File.ReadLines() also has an example that fits in with this discussion. Mar 21, 2016 at 11:04
0

Use String.Trim in a foreach loop, or if you are using .NET 3.5+ a LINQ statement.

0
0

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.