zoukankan      html  css  js  c++  java
  • C#统计字符出现个数

    做毕设时,需要统计汉语语料库中单词(单词已经粗切分)出现的频率,想到与我们开始学习C语言时统计字符串中每个字符出现的个数类似,就想用C#实现一下,发现泛型集合类Dictionary很有用,几行代码就搞定,爽!

    代码
    1 private static void FnCountWord()
    2 {
    3 String text = Console.ReadLine();
    4 Dictionary<Char, int> charDict = new Dictionary<char, int>();
    5 for (int i = 0; i < text.Length; i++)
    6 {
    7 if (charDict.ContainsKey(text[i]) == true)
    8 {
    9 charDict[text[i]]++;
    10 }
    11 else
    12 {
    13 charDict.Add(text[i], 1);
    14 }
    15 }
    16 //int编号,KeyValuePair<Char, int>中char字符,int统计字符数量
    17   Dictionary<int, KeyValuePair<Char, int>> charID = new Dictionary<int, KeyValuePair<Char, int>>();
    18 int k = 0;
    19 foreach (KeyValuePair<Char, int> charInfo in charDict)
    20 {
    21 charID.Add(k,charInfo);
    22 k++;
    23 }
    24 foreach (KeyValuePair<int, KeyValuePair<Char, int>> charInfo in charID)
    25 {
    26 Console.WriteLine("id={0},char={1},amount={2}", charInfo.Key, charInfo.Value.Key,charInfo.Value.Value);
    27 }
    28 }

  • 相关阅读:
    虚拟机的类加载机制
    数组
    Intellij快捷键
    Wireshark过滤器语法设置
    Git命令(转)
    Git命令
    字节码指令简介(转)
    Java异常了解
    Class类文件的结构
    垃圾收集器与内存分配策略(六)之内存分配与回收策略
  • 原文地址:https://www.cnblogs.com/qingliuyu/p/1893703.html
Copyright © 2011-2022 走看看