-3

我需要一些帮助。基本上,我在文本文件中有一段文本,我需要将文本文件(存储为字符串)读入字符列表并存储它们出现在字符串中的时间量。因此它将在 (AZ) 之间生成一个列表,并根据字符出现的次数对其进行排序。有没有办法在不使用 LINQ 的情况下做到这一点。

谢谢 :)

4

2 回答 2

3

您可以使用哈希表来执行此操作。

Hashtable listofChars = new Hashtable();

for () { // your loop for the chars in the file
        Char c ; // your char
        if (!listofChars.ContainsKey(c))
        {
            listofChars[c] = 1;
        }
        else {
            listofChars[c] = ((int)listofChars["c"]) + 1;
        } 
}

- 编辑 -

var listofChars = new SortedDictionary<char, int>();
foreach(char c in File.ReadAllText(fileName))
{
    if (!listofChars.ContainsKey(c))
    {
        listofChars[c] = 1;
    }
    else
    {
        listofChars[c] += 1;
    } 
}
于 2012-08-19T19:38:39.730 回答
1

一种有效且简单的方法是创建一个ConcurrentDictionary以 char 作为键并将其显示为值的数字。它有很好的AddOrUpdate (upsert) 方法:

string text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
var chars = new System.Collections.Concurrent.ConcurrentDictionary<char, int>();
foreach (char c in text)
{
   chars.AddOrUpdate(c, 1, (chr, count) => count + 1);
}

如果您想按没有 Linq(Lambda != Linq) 的编号订购它,您可以使用以下代码:

List<KeyValuePair<char, int>> charList = chars.ToList();
charList.Sort((firstPair, nextPair) =>
{
    return firstPair.Value.CompareTo(nextPair.Value);
});

编辑:如果您想订购降序更改以上一点:

charList.Sort((firstPair, nextPair) =>
{
    return -(firstPair.Value.CompareTo(nextPair.Value));
});

结果:

Console.Write(string.Join(Environment.NewLine, charList.Select(kv => string.Format("Char={0} Num={1}", kv.Key, kv.Value))));

Char=  Num=90
Char=e Num=59
Char=t Num=43
Char=s Num=39
Char=n Num=38
Char=i Num=32
Char=a Num=28
Char=o Num=25
Char=r Num=24
Char=p Num=18
Char=m Num=18
Char=l Num=17
Char=u Num=17
Char=d Num=16
Char=h Num=14
Char=y Num=13
Char=g Num=11
Char=c Num=10
Char=k Num=7
Char=w Num=6
Char=f Num=6
Char=I Num=6
Char=v Num=5
Char=b Num=5
Char=L Num=5
Char=, Num=4
Char=. Num=4
Char=0 Num=3
Char=x Num=2
Char=1 Num=2
Char=' Num=1
Char=5 Num=1
Char=M Num=1
Char=A Num=1
Char=P Num=1
Char=6 Num=1
Char=9 Num=1
于 2012-08-19T19:55:53.333 回答