Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of null/empty string values in a C# array

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?

like image 223
zohair Avatar asked Mar 11 '09 18:03

zohair


People also ask

Is empty string considered NULL in C?

The string exists in memory, so it's not a NULL pointer. It's just absent any elements. An empty string has a single element, the null character, '\0' . That's still a character, and the string has a length of zero, but it's not the same as a null string, which has no characters at all.

How remove NULL or empty from the list in C#?

RemoveAll() method accepts the Predicate<T> delegate that sets the conditions for the elements to be removed. To remove null, empty, and white-space characters from a list, you can use the predefined delegate IsNullOrWhiteSpace . Alternatively, you can use IsNullOrEmpty to remove null and empty strings from the List.

How do you remove Blank strings from an object?

To remove all empty string values from an object:Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array. Use the delete operator to delete each key with an empty string value.

Does an empty string count as NULL?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


Video Answer


2 Answers

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries); 
like image 76
Tamas Czinege Avatar answered Oct 02 '22 21:10

Tamas Czinege


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)); 
like image 44
sgriffinusa Avatar answered Oct 02 '22 20:10

sgriffinusa