简体   繁体   English

查找一个字符串数组中有多少个元素

[英]Finding how many elements are in a string array

I'm trying to find how many elements are in my string array, so I can add to that array from the first empty element. 我正在尝试查找字符串数组中有多少个元素,因此可以从第一个空元素添加到该数组中。

Here's what I've tried to do: 这是我尝试做的事情:

int arrayLength = 0;
string[] fullName = new string[50];

if (fullName.Length > 0)
{
    arrayLength = fullName.Length - 1;
}

and then from that refer to the first available empty element as: 然后从中引用第一个可用的空元素为:

fullName[arrayLength] = "Test";

I can also use this to see if the array is full or not, but my problem is arrayLength is always equal to 49, so my code seems to be counting the size of the entire array, not the size of the elements that are not empty. 我也可以使用它来查看数组是否已满,但是我的问题是arrayLength始终等于49,所以我的代码似乎是在计算整个数组的大小,而不是不为空的元素的大小。

Cheers! 干杯!

you can use this function to calculate the length of your array. 您可以使用此函数来计算数组的长度。

private int countArray(string[] arr)
{
    int res = arr.Length;

    foreach (string item in arr)
    {
        if (String.IsNullOrEmpty(item))
        {
            res -= 1;
        }
    }

    return res;
}

EDIT : To find the first empty element 编辑:查找第一个空元素

private int firstEmpty(string[] arr)
{
    int res = 0;

    foreach (string item in arr)
    {
        if (String.IsNullOrEmpty(item))
        {
            return res;
        }
        res++;
    }

    return -1; // Array is full
}

I'm trying to find how many elements are in my string array, 我试图找出我的字符串数组中有多少个元素,

array.Length

so I can add to that array from the first empty element. 因此我可以从第一个空元素添加到该数组。

Array's don't have empty elements; 数组没有空元素; there's always something in there, though it could be null . 尽管里面可能有null ,但总有东西。

You could find that by scanning through until you hit a null, or by keeping track each time you add a new element. 您可以通过扫描直到找到空值或每次添加新元素都保持跟踪来找到它。

If you're going to add new elements then, use List<string> this has an Add() method that will do what you want for you, as well as resizing when needed and so on. 如果要添加新元素,请使用List<string>它具有Add()方法,该方法将为您执行所需的操作,并在需要时调整大小等。

You can likely then just use the list for the next part of the task, but if you really need an array it has a ToArray() method which will give you one. 然后,您可能只将列表用于任务的下一部分,但是,如果您确实需要一个数组,则可以使用ToArray()方法为您提供一个方法。

因此,如果您想使用数组而不是列表,您仍然可以简单地获取空元素的数量,如下所示:

int numberOfEmptyElements = fullName.Count(x => String.IsNullOrEmpty(x));

Try the below code 试试下面的代码

    string[] fullName = new string[50];

    fullName[0] = "Rihana";
    fullName[1] = "Ronaldo";

    int result = fullName.Count(i => i != null);

in result you will have the number of occupied positions. result您将拥有几个职位。 In this case 2, cause 2 arrays are filled. 在这种情况下,2个原因被填充。 From there you can count the empty. 从那里您可以计算出空。 :) :)

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

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