在C#中,可以使用Dictionary
来实现字符串表到字典的转换。下面是一个示例代码:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// 定义字符串表
string[] stringTable = { "Key1=Value1", "Key2=Value2", "Key3=Value3" };
// 创建字典
Dictionary<string, string> dictionary = new Dictionary<string, string>();
// 将字符串表转换为字典
foreach (string keyValue in stringTable)
{
// 根据等号分割键值对
string[] parts = keyValue.Split('=');
// 添加键值对到字典
if (parts.Length == 2)
{
string key = parts[0];
string value = parts[1];
dictionary[key] = value;
}
}
// 打印字典中的内容
foreach (KeyValuePair<string, string> pair in dictionary)
{
Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);
}
}
}
上述代码中,首先定义了一个字符串表stringTable
,其中每个元素都是形如"Key=Value"的键值对。然后创建了一个Dictionary
对象dictionary
,用于存储键值对。接下来,通过foreach
循环遍历字符串表,将每个键值对拆分后添加到字典中。最后,使用foreach
循环遍历字典,打印出所有的键值对。
该代码的输出结果如下:
Key: Key1, Value: Value1
Key: Key2, Value: Value2
Key: Key3, Value: Value3
在实际应用中,可以根据具体场景灵活使用字符串表到字典的转换,例如读取配置文件、处理API响应等。此外,如果需要在C#中进行更复杂的字符串解析,可以使用正则表达式等工具进行匹配和提取。
领取专属 10元无门槛券
手把手带您无忧上云