Menu
CoddyTech

检查键是否存在

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 48 课,共 66 课。

要检查 HashMap(C# 中的字典)中是否存在某个键,可以使用 ContainsKey() 方法。

首先,创建一个字典:

Dictionary<string, int> ages = new Dictionary<string, int>();

添加一些键值对:

ages.Add("John", 25);
ages.Add("Mary", 30);

现在检查键是否存在:

bool exists = ages.ContainsKey("John");

运行上面的代码后,变量 exists 的值将为 true。

你可以在条件语句中使用它:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

挑战

简单

创建一个名为 CheckKeyExists 的方法,它接受两个参数:

  • 一个 Dictionary<string, int>(字典)
  • 一个要检查的字符串(键)

该方法应检查字典中是否存在这个键,并打印:

  • 如果找到这个键,则打印 "Key exists"
  • 如果没有找到这个键,则打印 "Key does not exist"

亲手试试

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // 在这里编写代码
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // 读取库存输入,支持 JSON 格式和逐行输入格式
        string firstLine = Console.ReadLine();
        
        // 检查输入是否为 JSON 格式
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // 处理 JSON 输入
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // 按引号外的逗号拆分
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // 使用正则表达式提取键和值
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器