简体   繁体   English

在指定索引处开始的数组中查找空字符串

[英]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). 我想检查索引3(其中值为4)是否存在空值。 I want to do this without splitting it inter two different arrays of strings. 我想做到这一点而不将其在两个不同的字符串数组之间拆分。

More specifically my example using an array named files 更具体地说,我的示例使用名为files的数组

string[] files;

I want to check from array index 8 to array index 28 if there are any empty values. 我想检查从数组索引8到数组索引28是否有空值。

您可以使用LINQ来做到这一点:

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

You can just use a for loop. 您可以只使用for循环。 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. 如果索引处或索引后的任何值为空,则将返回true。 If it reaches the end without finding one, it returns false. 如果到达末尾而没有找到一个,则返回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. 您不必一定要循环数组的末尾,您也可以将结束条件设置为指定的索引,例如,是否要检查索引5和10之间的空字符串,而不管是否存在在此之前或之后的任何时间。

Use LINQ:- 使用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);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM