Beginning C# 3.0: An Introduction to Object Oriented Programming
中的此代码这是一个程序,让用户在多行文本框中输入几个句子,然后计算每个字母在该文本中出现的次数
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]);
答案 0 :(得分:5)
count[index]++;
表示“在索引count
的{{1}}中为值添加1”。 index
具体称为递增。代码正在做的是计算一个字母的出现次数。
++
正在格式化输出行。使用string.Format,您首先传入一个格式说明符,其作用类似于模板或表单字母。 buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
和{
之间的部分指定了如何使用传递到}
的其他参数。让我分解格式规范:
{0, 4} The first (index 0) argument (which is the letter, in this case). The ,4 part means that when it is output, it should occupy 4 columns of text. {1,20} The second (index 1) argument (which is a space in this case). The ,20 is used to force the output to be 20 spaces instead of 1. {2} The third (index 2) argument (which is the count, in this case).
因此,当string.Format
运行时,string.Format
将用作第一个参数,并插入格式的(char)(i + LETTERA)
部分。 {0}
已插入" "
,{1}
已插入count[i]
。
答案 1 :(得分:3)
count[index]++;
这是后增量。如果要保存返回值,那么它将在递增之前计数[index],但它基本上只是递增值并在递增之前返回值。至于方括号内有变量的原因,它引用了数组索引中的值。换句话说,如果你想谈谈街上的第五辆车,你可能会考虑使用StreetCars(5)。好吧,在C#中我们使用方括号和零索引,所以我们会有类似StreetCars [4]的东西。如果你有一个Car数组调用StreetCars,你可以使用索引值引用第五辆汽车。
对于string.Format()方法,请查看this article。