我想在索引处获取整数数组的值。 GetValue方法拒绝int类型。 我究竟做错了什么? Ind是一个整数,locX的声明方式如下: public int[] locX; 我知道我做错了什么。 很抱歉这个问题,我对C#有点陌生。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我正在尝试创建一个过程来计算给定输入字符串中每个字母的频率。 到目前为止,除了在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]++;
}
}
}
问题是alphabetCount[index]++
计数alphabetCount[index]++
首先分配了alphabetCount[index]
计数alphabetCount[index]
,然后递增该值。 您需要使用预增量运算符:
alphabetCount[index] = ++alphabetCount[index];
您可以简单地重现此行为,如下所示:
var arr = new int[2];
arr[0] = arr[0]++;
Console.Write(arr[0]); // 0
您只需要编写alphabetCount[index]++;
或alphabetCount[index] = alphabetCount[index]+1;
(当量)
或者您使用linq:
string words = "Hello World";
Dictionary<char, int> counted = words.ToUpper().GroupBy(ch => ch).OrderBy(g => g.Key).ToDictionary(g => g.Key, g => g.Count());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.