6

I have a string array. I need to remove some items from that array. but I don't know the index of the items that need removing.

My array is : string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.

I need to remove the " " items. ie after removing " " my result should be arr={"a","b","c","d","e","f"}

how can I do this?

kamui
  • 3,339
  • 3
  • 26
  • 44
Nelson T Joseph
  • 2,683
  • 8
  • 39
  • 56
  • What version of .NET? Some LINQ extension methods introduced in .NET 3.5 would be perfect. – GregL Feb 21 '12 at 10:08
  • there are a few questions and answers like this already here. check out http://stackoverflow.com/questions/457453/remove-element-of-a-regular-array – Andrei G Feb 21 '12 at 10:08
  • Possible duplicate of [Remove blank values in the array using c#](https://stackoverflow.com/questions/8814811/remove-blank-values-in-the-array-using-c-sharp) – Jim Fell Oct 22 '18 at 14:27

4 Answers4

13
  string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "};
  arr = arr.Where(s => s != " ").ToArray();
BlueM
  • 6,523
  • 1
  • 25
  • 30
6

This will remove all entries that is null, empty, or just whitespaces:

arr.Where( s => !string.IsNullOrWhiteSpace(s)).ToArray();

If for some reason you only want to remove the entries with just one whitespace like in your example, you can modify it like this:

arr.Where( s => s != " ").ToArray();
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
2

Using LinQ

using System.Linq;


string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.
arr.Where( x => !string.IsNullOrWhiteSpace(x)).ToArray();

or depending on how you are filling the array you can do it before

string[] arr = stringToBeSplit.Split('/', StringSplitOptions.RemoveEmptyEntries);

then empty entries will not be put into your string array in the first place

kamui
  • 3,339
  • 3
  • 26
  • 44
0

You can use Except to remove blank value

string[] arr={" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.
arr= arr.Except(new List<string> { string.Empty }).ToArray();
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32