这段代码Beginning C# 3.0: An Introduction to Object Oriented Programming帮助我理解这个C#代码
这是有用户在多输入一两句的程序 - 行文本框,然后计算每个字母在文本
多少次出现private const int MAXLETTERS = 26; // Symbolic constants
private const int MAXCHARS = MAXLETTERS - 1;
private const int LETTERA = 65;
.........
private void btnCalc_Click(object sender, EventArgs e)
{
char oneLetter;
int index;
int i;
int length;
int[] count = new int[MAXLETTERS];
string input;
string buff;
length = txtInput.Text.Length;
if (length == 0) // Anything to count??
{
MessageBox.Show("You need to enter some text.", "Missing Input");
txtInput.Focus();
return;
}
input = txtInput.Text;
input = input.ToUpper();
for (i = 0; i < input.Length; i++) // Examine all letters.
{
oneLetter = input[i]; // Get a character
index = oneLetter - LETTERA; // Make into an index
if (index < 0 || index > MAXCHARS) // A letter??
continue; // Nope.
count[index]++; // Yep.
}
for (i = 0; i < MAXLETTERS; i++)
{
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
lstOutput.Items.Add(buff);
}
}
我不明白这行
count[index]++;
,这行代码
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
要建立在Surfer513的评论上,count是整数的“数组”。阵列就像火车上的汽车,每一个都有价值。所以,这段代码将一个字符转换为它的数字等价物,在数组中找到该位置,并将计数增加1,因为代码正试图记录字母频率。 – billinkc
@billinkc,很好的电话。我认为OP可以理解数组。 – 2011-08-17 00:26:10
我假设,因为他们没有质疑我的++位,它要么“混入”,要么是数组位。如果你愿意,可以随意把你的答案包装进你的答案 – billinkc