简体   繁体   English

字符计数

[英]Characters counting

Its weird,well i need to count characters from file, and in later computations use that information, now its weird part, i wanted to check if my program is correctly countig appearance of each character so i compared my results with monodevelop matches from ctrl+f for example for 'i' character my result is 518 monodevelop has 561 matches (with case sensitivity on), so maybe it coudl look like my programm does not count well but i made test and rewrited it to another file and again checked matches in mono develop now my results and monodevelop matches where same.它很奇怪,我需要从文件中计算字符数,并且在以后的计算中使用该信息,现在是奇怪的部分,我想检查我的程序是否正确计算了每个字符的出现,所以我将我的结果与来自 ctrl+ 的 monodevelop 匹配进行了比较f 例如对于“i”字符,我的结果是518 monodevelop 有561匹配项(区分大小写),所以可能看起来我的程序计算得不好,但我进行了测试并将其重写到另一个文件并再次检查匹配项mono develop 现在我的结果和 monodevelop 匹配相同。 Why is it happening ?为什么会这样?

here is code这是代码

public Histogram (String nazwa)
    {
        histogram = new Dictionary<string,float>();
        StringBuilder plik = odczytPliku.odczyt(nazwa);
        n = 0;
        foreach(char w in plik.ToString())
        {
            if(!histogram.ContainsKey(new string(w,1)))
                histogram.Add(new string(w,1),1);
            else
                histogram[new string(w,1)]+=1;
            n++;
        }

    }

The following code will create a histogram of characters in a string.以下代码将创建字符串中字符的直方图。 This assumes you're passing in the string correctly.这假设您正确地传递了字符串。

public Dictionary<char,int> Histogram( String myString )
{
    Dictionary<char,int> hist = new Dictionary<char,int>()

    if( !String.IsNullOrEmpty(myString) )
    {
        for( int i = 0; i < myString.Length; i++ )
        {
            char c = myString[i];

            if(hist.ContainsKey(c))
            {
                hist[c] = hist[c] + 1;
            }
            else
            {
                hist.Add(c,1);
            }
        }
    }

    return hist;
}
public Dictionary<char, int> Hist(string target)
    {
        return target.GroupBy(c => c)
            .ToDictionary(g => g.Key, g => g.Count());
    }

To make it case insensitive, just call it like this:要使其不区分大小写,只需像这样调用它:

var hist = Hist(target.ToUpperInvariant());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM