zoukankan      html  css  js  c++  java
  • 使用Dictionary键值对判断字符串中字符出现次数

    介绍Dictionary

    使用前需引入命名空间 using System.Collections.Generic

    Dictionary里面每一个元素都是一个键值对(由两个元素组成:键和值)

    键必须是唯一的,而值不需要唯一

    键和值都可以是任何类型(比如:string,int,自定义类型等)

    通过一个键读取一个值的时间接近0(1)

    键值对之间的偏序可以不定义

    使用Dictionary

    使用dictionary判断字符串中字符出现次数

    var dic = new Dictionary<char, int>();
    string str = "welcome to china,and bei jing huan ying ni";
    for (int i = 0; i < str.Length; i++)
    {
        if (!dic.ContainsKey(str[i]))//判断是否包含指定键名
        {
            dic.Add(str[i], 1);
        }
        else
        {
            dic[str[i]]++;//如果这个键值对中存在这个元素,就把个数加1
        }
    }
    //利用一个键值对KeyValuePair来访问这个元素
    foreach (KeyValuePair<char, int> item in dic)
    {
        Console.WriteLine("字符{0} {1}在这个句子中出现了{2}次", item.Key, (int)item.Key, item.Value);
    }
    Console.ReadKey();

    键值对中value是数组

    //键值对中value是数组
    var dic = new Dictionary<string, string[]>();
    string[] HuBei = { "wuhan", "tianmen", "xiantao" };
    string[] GuangDong = { "guangzhou", "shenzhen", "foshan" };
    dic.Add("HB", HuBei);
    dic.Add("GD", GuangDong);
    Console.WriteLine(dic["HB"][0]);
    Console.WriteLine(dic["GD"][1]);
    Console.ReadKey();

    键值对中value是类

    static void Main(string[] args)
    {          
        //键值对中value是类
        var stuList = new Dictionary<string, Student>();
        for (int i = 0; i < 3; i++)
        {
            Student stu = new Student();
            stu.Num = i.ToString();
            stu.Name = "Student" + i.ToString();
            stuList.Add(i.ToString(), stu);
        }
        foreach (var student in stuList)
        {
            Console.WriteLine("Output : Key {0}, Num : {1}, Name : {2}",
            student.Key, student.Value.Num, student.Value.Name);
        }
        Console.ReadKey();
    }
    
    public class Student
    {
        public string Num { get; set; }
        public string Name { get; set; }
    }

    End!

  • 相关阅读:
    创建数据库和表例子
    Python标准库之ConfigParser模块
    Python标准库之shelve模块(序列化与反序列化)
    Python标准库之shutil模块
    Python标准库之sys模块
    Python标准库之os模块
    Python标准库Random
    Python标准库之时间模块time与datatime模块详解
    Python模块导入详解
    Python目录结构规范
  • 原文地址:https://www.cnblogs.com/gygg/p/11609166.html
Copyright © 2011-2022 走看看