32

I have a string:

a = "1;2;3;"

And I would like to split it this way:

foreach (string b in a.split(';'))

How can I make sure that I return only 1, 2, 3 and not an 'empty string'?

If I split 1;2;3 then I will get what I want. But if I split 1;2;3; then I get an extra 'empty string'. I have taken suggestions and done this:

string[] batchstring = batch_idTextBox.Text.Split(';', StringSplitOptions.RemoveEmptyEntries);

However, I am getting these errors:

Error 1 The best overloaded method match for 'string.Split(params char[])' has some invalid arguments C:\Documents and Settings\agordon\My Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 36 EnterData

Error 2 Argument '2': cannot convert from 'System.StringSplitOptions' to 'char' C:\Documents and Settings\agordon\My Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 68 EnterData

Minhas Kamal
  • 20,752
  • 7
  • 62
  • 64
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

7 Answers7

66

String.Split takes an array when including any StringSplitOptions:

string[] batchstring = batch_idTextBox.Text.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);

If you don't need options, the syntax becomes easier:

string[] batchstring = batch_idTextBox.Text.Split(';');
qJake
  • 16,821
  • 17
  • 83
  • 135
22

Use StringSplitOptions.

a.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
Ry-
  • 218,210
  • 55
  • 464
  • 476
6

Pass StringSplitOptions.RemoveEmptyEntries to the Split method.

EDIT

The Split method does not have an overload to split by a single character. You need to specify an array of characters.

foo.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
Marlon
  • 19,924
  • 12
  • 70
  • 101
2

Didn't know about split options. If you didn't have that you could...

a.Split(';').Where(s => s.Length > 0).ToArray();
Eric Farr
  • 2,683
  • 21
  • 30
1
string line="Hello! Have nice day."
string[] substr = line.Split(new[] {' '}, 2);

Above code will split the line into two substrings based on first space. substr[0] will have "Hello!" substr[1] will have "Have nice day.". Here 2 in Split is an integer counter, you can pass any value based on your requirement.

Nagendra Reddy
  • 531
  • 5
  • 7
1

Give this a shot:

string test = "1;2;3;";
test = String.Join(",", test.TrimEnd((char)59).Split((char)59));

string test = "1;2;3;";
test = String.Join(",", test.TrimEnd(';').Split(';'));
James Johnson
  • 45,496
  • 8
  • 73
  • 110
1

Use

a.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

There are 4 overloads of .Split, two of them don't support StringSplitOptions and use the params format (so you don't need to create an array of splitters), two of them support StringSplitOptions and require an array of char or string.

shA.t
  • 16,580
  • 5
  • 54
  • 111
xanatos
  • 109,618
  • 12
  • 197
  • 280