gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:01:36 25 4
gpt4 key购买 nike

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

这是代码。

    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");
}
}
}

最佳答案

您可以简化计数器。

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]++;
}
}
}

关于c# - 更改 Int Array C# 中给定索引处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com