Getting rid of null/empty string values in a C# array
45,209
Solution 1
Try this:
yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
Solution 2
You could use the Where linq extension method to only return the non-null or empty values.
string someString = "1;2;;3;";
IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
Solution 3
public static string[] nullLessArray(string[] src)
{
Array.Sort(src);
Array.Reverse(src);
int index = Array.IndexOf(src, null);
string[] outputArray = new string[index];
for (int counter = 0; counter < index; counter++)
{
outputArray[counter] = src[counter];
}
return outputArray;
}
Author by
zohair
Updated on July 08, 2020Comments
-
zohair almost 4 years
I have a program where an array gets its data using string.Split(char[] delimiter). (using ';' as delimiter.)
Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:
1 ;2 ; ; 3;
This leads to my array having null values.
How do I get rid of them?
-
Tamas Czinege about 15 yearsYou could possibly insert a .Select(s => s.Trim()) between Split and Where so that whitespace-only strings will get removed as well.
-
Guffa about 15 yearsThat does not compile. You need to use new char[]{';'} as the first parameter.
-
Guffa about 15 yearsNote: The Split method never produces null values.
-
denver over 10 yearsOne thing to note is that this will not remove strings consisting of only whitespace.
-
PSR over 7 years@TamasCzinege you can use string.IsNullOrWhiteSpaces instead of trim()
-
PSR over 7 yearsNot works as expected. ex: var a = "1" + "," + "" + "," + "2" + "," + " " + "," + "3" + "," + " " + "," + null + ","+"4"; . a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); . Console.WriteLine(a.ToString()); will give result of 1,,2, ,3, ,,4