C#:调整字符串数组的大小

本文关键字:数组 字符串 调整 | 更新日期: 2023-09-27 18:31:36

我是编程新手,我决定通过根据用户输入创建一个随机单词生成器来给自己一个挑战。我正在尝试将用户的话放在数组中,然后显示数组中的随机单词。当我运行程序时,我最多可以输入四个单词,然后收到一个错误:"数组索引超出范围。

我可以调整数组大小的次数有限制吗?

using System;
namespace RandomWordGenerator
{
class MainClass
{
    public static void Main (string[] args)
    {
        Random r = new Random ();
        string[] words = new string[1];
        Console.WriteLine ("Enter words for the random word generator. ");
        int a = 0;
        while(!(Console.ReadLine().Equals("END"))){
            words[a] = Console.ReadLine();
            a++;
            Array.Resize(ref words, a);
        }
        Console.WriteLine ();
        Console.WriteLine (words[r.Next (a)]);
    }
}
}

C#:调整字符串数组的大小

c# 中的数组是不可变的,也就是说,它们在创建后无法更改。

你想要的是一个 List<string> ,可以随意调整大小。

class MainClass
{
    public static void Main (string[] args)
    {
        Random r = new Random ();
        List<string> words = new List<string>();
        Console.WriteLine ("Enter words for the random word generator. ");
        int a = 0;
        while(!(Console.ReadLine().Equals("END"))){
            words.Add(Console.ReadLine());
       }
        Console.WriteLine ();
        Console.WriteLine (words[r.Next(words.Count)]);
    }
}

Array.Resize实际上命名得不是很好,因为它的作用与实际调整大小不同。从 MSDN 文档:

此方法分配一个具有指定大小的新数组,将元素从旧数组复制到新数组,然后用新数组替换旧数组。

List<>类是为动态大小的集合而设计的,在许多情况下是比原始数组更好的选择。

您看到IndexOutOfRangeException的原因是您尝试访问索引超出其当前范围的数组:

int a = 0;
while(!(Console.ReadLine().Equals("END")))
{
    words[a] = Console.ReadLine();
    a++;
    Array.Resize(ref words, a);
}

在第一次迭代之后,您尝试访问 words[a] where a = 1 ,但数组索引从零开始,因此您尝试访问数组只有 1 个元素位于words[0]索引words[1],因为您分配了一个带有 Array.Resize 的新数组,传递a (1)作为其大小。这就是您看到异常的原因。

如@rossipedia所述,您的解决方案存在问题。只需使用List<T>.

关于使用List的建议都是好的和有效的,但对你的具体问题的直接回答如下——

Array.Resize(ref words, a);

应改为 -

Array.Resize(ref words, a + 1);

原因 - 您从 a=0; 开始,将 words[0] 设置为值读取,设置 a=1 ,然后要求运行时将数组大小从大小从 1 调整为 1