查找未知大小数组的大小

时间:2016-04-02 01:56:06

标签: c# arrays

我想声明一个空数组,它接受来自用户的输入,然后找到该数组的长度。我已经声明了空数组,但不知道如何从用户那里获取输入。

1 个答案:

答案 0 :(得分:0)

以下是您要求的确切示例:https://dotnetfiddle.net/1RSPzs

using System;

public class Program
{
    public static void Main()
    {
        var index = 0;
        var myArray = new string[] {};
        var isEmptyText = false;
        do
        {
            Console.Write("Give me some input or press enter to quit: ");
            var result = Console.ReadLine();
            isEmptyText = string.IsNullOrWhiteSpace(result);
            if (!isEmptyText) 
            {
                if (myArray.Length <= index) 
                {
                    Array.Resize(ref myArray, index+1);
                }

                myArray[index++] = result;
            }
        } while (!isEmptyText);

        Console.WriteLine(myArray.Length);
        Console.WriteLine(string.Join(", ", myArray));
    }
}

虽然该代码有效,但它会不断重新调整阵列大小,这是一个代价高昂的过程。我会建议给它一个合理数量的物品,它们只在需要时重新调整尺寸。像这样:

using System;

public class Program
{
    public static void Main()
    {
        var index = 0;
        var myArray = new string[25];
        var isEmptyText = false;
        do
        {
            Console.Write("Give me some input or press enter to quit: ");
            var result = Console.ReadLine();
            isEmptyText = string.IsNullOrWhiteSpace(result);
            if (!isEmptyText) 
            {
                if (myArray.Length <= index) 
                {
                    Array.Resize(ref myArray, myArray.Length + 10);
                }

                myArray[index++] = result;
            }
        } while (!isEmptyText);

        Console.WriteLine(myArray.Length);
        for (var i=0; i < index; i++) 
        {
            Console.Write((i==0 ? "" : ", ") + myArray[i]);
        }
    }
}

当然,最好的办法是使用更多现代数据结构,如链接列表或向量,但有时我们会在学校获得这些任务,并且必须弄明白。查看通用集合,了解在C#中使用的最简单数据结构:http://www.csharp-station.com/Tutorial/CSharp/Lesson20