回顾:HashMap 操作
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 55 课,共 66 课。
挑战
中等创建一个名为 ProcessDictionary 的方法,对 Dictionary<string, int> 库存执行高级操作。该方法应当:
- 处理操作列表中的命令:
COUNT:打印Total items: {count}(其中{count}是不同键的数量),然后打印成功消息ADD item quantity:添加具有指定数量的新物品(如果物品已存在,则增加其数量),然后打印成功消息REMOVE item:从库存中移除指定物品,然后打印成功或失败消息UPDATE item quantity:将物品的数量设为指定值,然后打印成功或失败消息FIND item:如果找到,则打印{item}: {quantity},然后打印成功消息;如果未找到,则打印Not found,然后打印失败消息
- 对于每个操作,按以下确切格式打印状态消息:
Operation {command} performed successfullyOperation {command} failed: {reason}。其中,当物品不在库存中时,{reason}为Item not found
- 返回更新后的库存字典
例如,在包含
orange: 3 的库存中处理 FIND orange,应打印:orange: 3Operation FIND performed successfully当
shoes 不在库存中时处理 REMOVE shoes,应打印:Operation REMOVE failed: Item not found亲手试试
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static Dictionary<string, int> ProcessDictionary(Dictionary<string, int> inventory, List<string> operations)
{
// 在这里编写你的代码
return inventory;
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
List<string> operations = new List<string>();
// 读取第一行,检查库存是否采用 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);
}
}
// Read second line for operations
string secondLine = Console.ReadLine();
// Check if operations are in JSON array format
if (secondLine != null && secondLine.StartsWith("[") && secondLine.EndsWith("]"))
{
try
{
// Extract content between square brackets
string arrayContent = secondLine.Substring(1, secondLine.Length - 2);
// Use regex to match all quoted strings - this is more robust
MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
foreach (Match match in matches)
{
// Add the captured group (without quotes)
if (match.Groups.Count > 1)
{
operations.Add(match.Groups[1].Value);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing operations array: {ex.Message}");
return;
}
}
else
{
// Process operations in traditional format
int m = int.Parse(secondLine);
for (int i = 0; i < m; i++)
{
operations.Add(Console.ReadLine());
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing JSON input: {ex.Message}");
return;
}
}
else
{
// Process traditional input format
int n = int.Parse(firstLine);
for (int i = 0; i < n; i++)
{
string[] parts = Console.ReadLine().Split(':');
inventory.Add(parts[0], int.Parse(parts[1]));
}
// Read operations
int m = int.Parse(Console.ReadLine());
for (int i = 0; i < m; i++)
{
operations.Add(Console.ReadLine());
}
}
Dictionary<string, int> result = ProcessDictionary(inventory, operations);
// Print updated inventory
Console.WriteLine("Final Inventory:");
foreach (var item in result)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}逻辑与流程中的所有课
自己练习: C# 在线编译器