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

0

7 Answers 7

68

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(';');
Sign up to request clarification or add additional context in comments.

Comments

22

Use StringSplitOptions.

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

Comments

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);

Comments

2

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

a.Split(';').Where(s => s.Length > 0).ToArray();

Comments

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(';'));

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.