在Int Array C#中更改给定索引处的值

Change value at given index in Int Array C#

我试图创建一个过程来计算给定输入字符串中每个字母的频率。到目前为止,除了在int数组中的给定索引处更新int的值外,我所拥有的代码似乎工作得很好。当我调试代码时,它成功地找到了与当前字符相对应的字符串数组的索引,所以问题似乎出在行:alphabetCount[index] = alphabetCount[index]++;上。

这是密码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    string[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    int[] alphabetCount = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    string baseInput = string.Empty;

    private void button_count1_Click(object sender, EventArgs e)
    {
        baseInput = textBox_base.Text.ToUpper();
        int length = baseInput.Length;

        for (int i = 0; i < length; i++)
        {
            try
            {
                int index = Array.IndexOf(alphabet,baseInput[i].ToString());
                alphabetCount[index] = alphabetCount[index]++;
            }
            catch
            {
                //MessageBox.Show("nope");
            }
        }
    }


您可以简化计数器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int[] alphabetCount =
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string baseInput = string.Empty;

private void button_count1_Click(object sender, EventArgs e)
{
    baseInput = textBox_base.Text.ToUpper();

    foreach(var character in baseInput)
    {
        if(char.IsLetter(baseInput))
        {
            // A is ASCII 65, Z is ASCII 90
            // Subtract 65 to put it in the alphabetCount range
            var index = character - 65;
            alphabetCount[index]++;
        }
    }
}


问题是alphabetCount[index]++首先分配alphabetCount[index]然后增加值。您需要使用预增量运算符来代替:

1
alphabetCount[index] = ++alphabetCount[index];

您可以简单地复制这种行为:

1
2
3
4
var arr = new int[2];
arr[0] = arr[0]++;

Console.Write(arr[0]); // 0


你只需要写alphabetCount[index]++;alphabetCount[index] = alphabetCount[index]+1;(相当于)

或者使用LINQ:

1
2
string words ="Hello World";
Dictionary<char, int> counted = words.ToUpper().GroupBy(ch => ch).OrderBy(g => g.Key).ToDictionary(g => g.Key, g => g.Count());