Mark
Mark

Reputation: 2760

Split string in c#, empty space also considered as string how to discard empty string

I have a text box where I enter the input as

"Two; [email protected];"

string[] result = txt_to.Text.Split(';');

so what happens here is the result takes three strings. 1. two 2. [email protected] 3. "" (empty space) since there is a ; after the email it considers that as a string how can I discard the 3rd string that it takes. It happens when I enter the email and a semicolon and press the space bar it throws a error. If it is just space after the semicolon the split should discard it how to do that

Upvotes: 5

Views: 3697

Answers (6)

Eng Mohamed Attian
Eng Mohamed Attian

Reputation: 97

string s=txt_to.Text;
s = s.Replace(" ", "");
string[] result = s.Split(';');

Upvotes: 0

deostroll
deostroll

Reputation: 11975

var arr = mystring.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 6

Matthias
Matthias

Reputation: 1799

It looks to me like it would make sense to discard empty strings from the result anyway, not only at the end. If this is the case, you could use

char[] separators = new char[]{';'};
string[] result = txt_to.Text.Split(separators , StringSplitOptions.RemoveEmptyEntries);

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

I'm gathering you want to split the string into a number of strings, but exclude any "empty" strings (those consisting only of whitespace)? This ought to help you out...

string[] result = txt_to.Text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 12

mamoo
mamoo

Reputation: 8166

Call the same method, adding StringSplitOptions.RemoveEmptyEntries

http://msdn.microsoft.com/it-it/library/tabh47cf.aspx

Upvotes: 2

Stecya
Stecya

Reputation: 23266

Pass StringSplitOptions parameter

var result = yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 3

Related Questions