-2

I have a string that contains email addresses like this :

string emailIDs = "xyz@gmail.com;abc@yahoo.com;frog@gmail.com;whyme@hotmail.com;"

I want to add these emails in List. I tried splitting it at ';' but this creates an extra record in the list which causes a null exception. I want to split and add this to my List without any extra record. Please let me know how can I achieve this in c#?

I am trying like this:

List<string> To = new List<string>(emailIDs.Cc.Split(new[] { ";" },StringSplitOptions.RemoveEmptyEntries));

Following is the result: enter image description here

I am trying to remove this extra record at the end be cause Cc contains only two records: enter image description here

Divya
  • 9
  • 1
  • 6
  • duplicate of [this](https://stackoverflow.com/questions/17571841/split-comma-separated-values) , just a different seperator – MDT Mar 30 '20 at 14:06

1 Answers1

1

Use StringSplitOptions.RemoveEmptyEntries to get rid of blank entries when splitting.

See documentation: https://learn.microsoft.com/en-us/dotnet/api/system.stringsplitoptions?view=netframework-4.8

Example:

var list = emailIDs.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);

Edit:

I think that the string you posted "xyz@gmail.com;abc@yahoo.com;frog@gmail.com;whyme@hotmail.com;" does not match the actual string you are passing to String.Split() method. Looking closely at the end of email.Cc, it contains whitespace at the end, generating a non-empty but blank string that will not be removed by StringSplitOptions.RemoveEmptyEntries.

What about trimming that whitespace before?

var list = emailIDs.TrimEnd().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    ^^^^^^^^^
Yotam Salmon
  • 2,400
  • 22
  • 36