tags:

views:

310

answers:

7

i have a string that comes in like:

 string email = "[email protected], [email protected], [email protected]";

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] = "[email protected]"
 emails[1] = " [email protected]"
 emails[2] = " [email protected]"

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] = "[email protected]"
 emails[1] = "[email protected]"
 emails[2] = "[email protected]"
+3  A: 

You can use Trim():

string email = "[email protected], [email protected], [email protected]";
string[] emails = email.Split(',');
emails = (from e in emails
          select e.Trim()).ToArray();
skalburgi
exactly what I was going to say
Oplopanax
after i run this code and look at emails in the IDE, it still has the spaces in front of all non zero items
ooo
You're right, Trim() returns a new string. I've edited in one that should work.
skalburgi
This answer is correct but is overkill, this answer has the best approach: http://stackoverflow.com/questions/1355704/trim-all-strings-in-an-array/1355732#1355732
Andrew Hare
A: 

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

jscharf
A: 

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.

Jan Zich
+3  A: 

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

string email = "[email protected], [email protected], [email protected]";    
string[] emails = email.Replace(' ', '').Split(',');
-1 (only because it was marked as *the* answer) While this does put the required text in the array, it's not the most expressive use of the available API.
280Z28
+6  A: 

Use Regex.Split to avoid trimming

var emails = Regex.Split(email, @",\s*");
Brian Rasmussen
+8  A: 

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);
280Z28
+1 This is the best answer.
Andrew Hare
+1 I didn't know about the options. Coming from Perl I see regexs everywhere. With the options Split is the way to go.
Brian Rasmussen
+1 we use LINQ so much that we tend to forget that other elegant options do exist.
Stan R.
+1 Great answer. I didn't know also about this.
+1  A: 
emails.Split(',').Select(email => email.Trim()).ToArray()
Bryan Watts