2011-08-17 125 views
0

这段代码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]); 

回答

3
count[index]++; 

这是一个后递增。如果要保存返回值,那么在增量之前应该是count [index],但它基本上所做的就是增加值并在增量之前返回值。至于方括号内有变量的原因,它是在数组的索引中引用一个值。换句话说,如果你想谈论街上的第五辆车,你可以考虑像StreetCars(5)这样的东西。那么,在C#中我们使用方括号和零索引,所以我们会有类似StreetCars [4]的东西。如果您有Car数组调用StreetCars,则可以使用索引值引用第5辆汽车。

至于string.Format()方法,请查看this article

+1

要建立在Surfer513的评论上,count是整数的“数组”。阵列就像火车上的汽车,每一个都有价值。所以,这段代码将一个字符转换为它的数字等价物,在数组中找到该位置,并将计数增加1,因为代码正试图记录字母频率。 – billinkc

+0

@billinkc,很好的电话。我认为OP可以理解数组。 – 2011-08-17 00:26:10

+1

我假设,因为他们没有质疑我的++位,它要么“混入”,要么是数组位。如果你愿意,可以随意把你的答案包装进你的答案 – billinkc

5

count[index]++;的意思是“在索引index上将012加到count的值上”。 ++被具体称为递增。代码正在做的是统计一封信件的出现次数。

buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);正在格式化一行输出。使用string.Format时,首先传入格式说明符,其工作方式类似于模板或表单字母。 {}之间的部分指定如何使用传递到string.Format的附加参数。让我打破的格式规范:当string.Format运行,(char)(i + LETTERA)作为第一个参数,插入格式的{0}部分

 
{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). 

左右。 " "插入{1}count[i]插入{2}

+0

非常感谢您的回答 – tito11