user3913587
user3913587

Reputation: 41

Finding an empty string in an array beginning at a specified index

I want to check if an empty string exists in an array after a specified index.

Suppose I have this array:

string[] values = {"1", "2", "2", "4", "", "", ""};

I want to check if an empty value exists from index 3 (where the value is 4). I want to do this without splitting it inter two different arrays of strings.

More specifically my example using an array named files

string[] files;

I want to check from array index 8 to array index 28 if there are any empty values.

Upvotes: 0

Views: 355

Answers (3)

Rahul Singh
Rahul Singh

Reputation: 21795

Use LINQ:-

string[] Values = { "1", "2", "2", "4", "", "", "" };
            int specifiedIndex = 3;
            var query1 = Values.Skip(specifiedIndex).Select((v, index) => new { v, index }).Where(x => x.v == String.Empty).Select(z => z.index + specifiedIndex);

            foreach (var val in query1)
            {
                Console.WriteLine(val);
            }

Upvotes: 0

Ilian
Ilian

Reputation: 5355

You can do it with LINQ:

files.Skip(index).Any(s => s == string.Empty);

Upvotes: 3

AdamMc331
AdamMc331

Reputation: 16690

You can just use a for loop. Try this:

for(int i = specifiedIndex; i < array.Length; i++)
{
    if(array[i].Equals(""))
        return true;
}
return false;

This will return true if any of the values at or after the index are empty. If it reaches the end without finding one, it returns false.

You can adjust this to fit your needs. You don't necessarily have to loop the the end of the array, you can set the end condition to a specified index too, say if you wanted to check for an empty string between indexes 5 and 10 but don't care if there are any before or after that.

Upvotes: 0

Related Questions