Rod
Rod

Reputation: 15457

how would you remove the blank entry from array

How would you remove the blank item from the array?

Iterate and assign non-blank items to new array?

String test = "John, Jane";

//Without using the test.Replace(" ", "");

String[] toList = test.Split(',', ' ', ';');

Upvotes: 8

Views: 8089

Answers (7)

Greg Buehler
Greg Buehler

Reputation: 3894

string[] toList = test.Split(',', ' ', ';').Where(v => !string.IsNullOrEmpty(v.Trim())).ToArray();

Upvotes: 0

Guffa
Guffa

Reputation: 700302

If the separator is followed by a space, you can just include it in the separator:

String[] toList = test.Split(
  new string[] { ", ", "; " },
  StringSplitOptions.None
);

If the separator also occurs without the trailing space, you can include those too:

String[] toList = test.Split(
  new string[] { ", ", "; ", ",", ";" },
  StringSplitOptions.None
);

Note: If the string contains truely empty items, they will be preserved. I.e. "Dirk, , Arthur" will not give the same result as "Dirk, Arthur".

Upvotes: 0

jonnyb
jonnyb

Reputation: 353

Try this out using a little LINQ:

var n = Array.FindAll(test, str => str.Trim() != string.Empty);

Upvotes: 1

RQDQ
RQDQ

Reputation: 15569

string[] result = toList.Where(c => c != ' ').ToArray();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500385

You would use the overload of string.Split which allows the suppression of empty items:

String test = "John, Jane";
String[] toList = test.Split(new char[] { ',', ' ', ';' }, 
                             StringSplitOptions.RemoveEmptyEntries);

Or even better, you wouldn't create a new array each time:

 private static readonly char[] Delimiters = { ',', ' ', ';' };
 // Alternatively, if you find it more readable...
 // private static readonly char[] Delimiters = ", ;".ToCharArray();

 ...

 String[] toList = test.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);

Split doesn't modify the list, so that should be fine.

Upvotes: 5

Davide Piras
Davide Piras

Reputation: 44605

You can put them in a list then call the toArray method of the list, or with LINQ you could probably just select the non blank and do toArray.

Upvotes: 0

Tim Lloyd
Tim Lloyd

Reputation: 38434

Use the overload of string.Split that takes a StringSplitOptions:

String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 26

Related Questions