从文本文件C#中计算字符数 [英] Count character from text file C#

查看:182
本文介绍了从文本文件C#中计算字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个示例程序WPF,它将使用openfiledialouge读取text.txt文件,并在文本框中显示每个字符的结果出现,包括特殊字符(〜!@#%^& *()_ + - ) 。

我写的是将文件的所有内容写入文本框。

我想计算文本框中每个字符和输出的出现次数。



样本输出:

I m writing a sample programs WPF which will read a text.txt file with openfiledialouge and will show result occurrence of each character including special characters(~!@#$%^&*()_+-) 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





< b>我尝试了什么:





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;

    }

}

推荐答案

%^& *()_ + - )在文本框中。

我写的是将文件的所有内容写入文本框。

我想计算文本框中每个字符和输出的出现次数。



样本输出:

%^&*()_+-) 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 a Dictionary<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);
    }


这篇关于从文本文件C#中计算字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆