更新时间:2023-11-23 11:22:34
%^& *()_ + - )在文本框中。
我写的是将文件的所有内容写入文本框。
我想计算文本框中每个字符和输出的出现次数。
样本输出:
%^&*()_+-) in textbox.
what i wrote is write all content of file to textbox.
I want to count occurrence of each character and output in textbox.
Sample output:
<pre><pre>Number of 'a':10
Number of 'b':20
Number of '@':5
。
。
.
.
Number of 'z':15
我尝试了什么:
What I have tried:
protected void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog()==true)
{
string filepath = openFile.FileName;
textbox.Text = File.ReadAllText(filepath);
readbar.Value = 100;
}
}
你可以使用字典< char,int>
计算每个字符的出现次数。
You could use aDictionary<char, int>
to count each character's occurrences.
Dictionary<char, int> occurrences = new Dictionary<char, int>();
string text = File.ReadAllText(filepath);
foreach (char c in text) {
if (!occurrences.ContainsKey(c)) {
occurrences.Add(c, 1);
}
else {
occurrences[c]++;
}
}
您将以字符串中每个字符的出现次数结束。但是如果您的输入文本文件包含无法用简单的 char
值表示的unicode字符,则可能会变得更加困难。
You will end with the number of occurrences of each character in the string. But it may get a little more difficult if your input text file contains unicode characters which cannot be represented by a simple char
value.
试试这个:
Try this:
string content = "ABCDEFFGGGHHHHIIIII";
var differentChars = content.GroupBy(g => g).Select (g => new {c = (char) g.Key, count = g.Count()});
然后你可以使用 foreach
You can then use foreach
foreach (var pair in differentChars)
{
Console.WriteLine("{0}:{1}", pair.c, pair.count);
}