Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

asp.net

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

like image 788
Mark Avatar asked Oct 21 '11 12:10

Mark


People also ask

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What does split do in C?

// Splits str[] according to given delimiters. // and returns next token. It needs to be called // in a loop to get all tokens. It returns NULL // when there are no more tokens.

What is string split () and give its syntax?

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

What does strtok () do in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


2 Answers

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);
like image 128
Grant Thomas Avatar answered Sep 28 '22 04:09

Grant Thomas


var arr = mystring.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries);
like image 33
deostroll Avatar answered Sep 28 '22 05:09

deostroll