c# - 我似乎无法理解此 C# 代码中用于从输入字段中计算字符的当前错误
问题描述
这是我的代码,任何帮助/建议都会有所帮助!提前致谢!
我正在创建一个计算输入字段中字符的表单。我想我大部分都写对了,但是我得到了一些错误:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Wk5Ch12Exer9
{
public partial class Form1 : Form
{
String inputText = null;
// How do I decide on below number?
int[] charFrequency = new int[52];
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
inputText = rtbInputArea.Text;
}
private void processLine(String strng)
{
if (strng.Equals(null))
return;
char[] current = strng.ToCharArray();
for (int idx = 0; idx < current.Length; idx++)
{
try
{
if (current[idx]>= 65 &&
current[idx] <= 90)
{
charFrequency[current[idx] - 65] += 1;
}
else if (current[idx] >= 97 &&
current[idx] <= 122)
{
charFrequency[current[idx] - 97 + 26] += 1;
}
}
catch (Exception)
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder output = new StringBuilder("");
String[] inp = inputText.Split('\n');
for (int idx = 0; idx < inp.Length; idx++)
{
processLine(inp[idx]);
}
for (int ins = 0; ins < 26; ins++)
{
if (charFrequency[ins] != 0)
{
output.Append("Frequency of " +
(char)(ins + 65) + " is: " +
charFrequency[ins] + "\n");
}
}
for (int ins = 26; ins < charFrequency.Length; ins++)
{
if (charFrequency[ins] != 0)
{
outputAppend("Frequency of " +
(char)(ins + 97 - 26) +
" is: " +
charFrequency[ins] + "\n");
}
}
rtbOutputArea.Text = output.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
rtbInputArea.Text = "";
rtbOutputArea_TextChanged.Text = "";
charFrequency = new int[52];
}
}
}
我真的非常迷失在我要做的事情上。我一直在谷歌上搜索,最终变得更加困惑。
解决方案
从字典开始:
var dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
.ToDictionary(k=>k,k=>0);
检查字符串中的字符是否在字典中,如果是,则递增:
if (dict.ContainsKey(c))
{
dict[c]+=1;
}
输出:
var s = dict
.Where(k=>k.Value>0)
.Select(k=>$"Frequency of {k.Key} is {k.Value}")
var output = string.Join("\n", s);
或使用 Linq GroupBy:
var strng = "This is just a test.";
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
.ToCharArray();
var g = strng
.Where(arr.Contains)
.GroupBy(s=>s)
.OrderBy(s=>s.Key)
.Select(s=>$"Frequency of {s.Key} is {s.Count()}");
var output = string.Join("\n", g);
推荐阅读
- python - Python 上的指数衰减曲线拟合。错误:优化警告
- node.js - 在 Node.js 中执行图像压缩后,无法从前端获取图像 URL
- php - Pulling random object out of array of objects
- angular - 如何在登陆时默认打开带有孩子的完整树?
- javascript - Material-UI 多表折叠/展开
- node.js - 使用 readline-sync 问题时 Node REPL 意外退出
- plsql - PL SQL 删除非 Ascii 字符,但不删除回车符
- javascript - 如何在 JQuery 中将 outerHTML 作为字符串返回?
- ios - 无法将简单的“yyyy:MM:dd HH:mm:ss”转换为日期对象。任何解决方案
- sorting - Kotlin while 循环不适用于三个条件