【发布时间】:2021-02-11 23:56:01
【问题描述】:
首先,我对编码很陌生,所以如果这很简单,我很抱歉,我正在尝试编写一个程序,从输入数据中计算每行元音的数量,然后显示每行的计数。我在尝试设置将存储总计数的列表的初始容量时遇到了一个问题,即使 letter.Count = 15,容量也会保持为零。以下是我所拥有的,谢谢你的任何以及所有反馈:
var letters = new List<string>();
var vowels = new char[] { 'a', 'e', 'i', 'o', 'u'};
string input;
while (!String.IsNullOrWhiteSpace(input = Console.ReadLine()))
{
letters.Add(input);
if (letters.Count == input.Length)
break;
}
var length = letters.Count;
var total = new List<int>(length);
【问题讨论】:
-
“容量一直设置为零” -- 不,它没有。它被设置为
length,就像你的代码所说的那样。问题是您没有费心阅读文档,其中特别提到了"Capacity is the number of elements that the List<T> can store before resizing is required, whereas Count is the number of elements that are actually in the List<T>."。请参阅副本了解如何设置列表中的实际元素计数。 -
如果要提前指定总大小,请使用数组。列表的构建是为了通过根据需要在内部调整数组大小来解决该限制。容量属性只是设置初始大小以避免在列表填充期间大量调整大小。