在字典中添加字符

本文关键字:字符 添加 字典 | 更新日期: 2023-09-27 18:02:44

在我的程序中,我有一段代码在字典中添加字符

 var listOfSimilarCharacters = new Dictionary<string, string>();
 listOfSimilarCharacters.Add("l", "!");
 listOfSimilarCharacters.Add("1", "i");
 listOfSimilarCharacters.Add("O", "0");
 listOfSimilarCharacters.Add("o", "I");

但是在上面我的代码中,我有一个属性"SimilarCharacters",我需要将其剔除并删除四个listOfSimilarCharacters.Add

/// <summary>
/// A constant that is lists all similar characters.
/// </summary>
public const string SimilarCharacters = "l!1iO0oI";

在某种程度上,我需要在字典中添加SimilarCharacters中的字符并读取SimilarCharacters,以便我可以使用它而不是四行。

在字典中添加字符

        string SimilarCharacters = "l!1iO0oI";
        var listOfSimilarCharacters = new Dictionary<string, string>();
        bool timeToAdd = false;
        string key = String.Empty;
        string value = String.Empty;
        foreach ( var c in SimilarCharacters )
        {
            if ( timeToAdd )
            {
                value = c.ToString();
                listOfSimilarCharacters.Add( key, value );
            }
            else
            {
                key = c.ToString();
            }
            timeToAdd = !timeToAdd;
        }

你可以使用集合初始化器来填充你的字典:

var listOfSimilarCharacters = new Dictionary<string, string> { 
  { "l", "!" }, { "1", "i" }, {"O", "0"}, {"o", "I"} 
};

顺便说一句,为什么你使用字符串来存储字符?