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?

3
  • What version of .NET? Some LINQ extension methods introduced in .NET 3.5 would be perfect. Commented Feb 21, 2012 at 10:08
  • there are a few questions and answers like this already here. check out stackoverflow.com/questions/457453/… Commented Feb 21, 2012 at 10:08
  • Possible duplicate of Remove blank values in the array using c# Commented Oct 22, 2018 at 14:27

4 Answers 4

13
  string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "};
  arr = arr.Where(s => s != " ").ToArray();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

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.