简体   繁体   English

如何使var输入不区分大小写的字典-C#

[英]how to make a case insensitive dictionary for var input - C#

var fruitDictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { { "Apple" , "Fruit" }, { "Orange", "Fruit" }, { "Spinach", "Greens" } };

        TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
        string data = textRange.Text;
        var output = new StringBuilder(data);

        foreach (var kvp in fruitDictionary)
            output.Replace(kvp.Key, kvp.Value);

        var result = output.ToString();
        richTextBox2.AppendText(result);

It works normally but if the input isnt in format it wont work. 它可以正常工作,但是如果输入格式不正确,它将无法正常工作。 For example on Apple the output is Fruit but on apple it still says apple 例如,在Apple上,输出为Fruit,但在Apple上,仍显示为apple

By setting the dictionary's comparer to StringComparer.InvariantCultureIgnoreCase , key lookup became culture and case invariant -- ie var a = fruitDictionary["apple"]; 通过将字典的比较器设置为StringComparer.InvariantCultureIgnoreCase ,关键字查找将变为区域性var a = fruitDictionary["apple"];区分大小写-例如, var a = fruitDictionary["apple"]; and var b = fruitDictionary["ApPlE"] will yield the same results. 并且var b = fruitDictionary["ApPlE"]将产生相同的结果。 That said, you perform your replace operation on an instance of StringBuilder which is not related to that. 就是说,您对与此无关的StringBuilder实例执行替换操作。 Both StringBuilder.Replace and String.Replace don't have overloads that let you configure string comparison options, so you would have to make an extension method. StringBuilder.ReplaceString.Replace都没有让您配置字符串比较选项的重载,因此您必须制作一个扩展方法。

public static string Replace(this string str, string oldValue, string newValue,
            StringComparison comparison = StringComparison.Ordinal)
{
    var index = str.IndexOf(oldValue, comparison);
    while (index >= 0)
    {
        str = str.Remove(index, oldValue.Length);
        str = str.Insert(index, newValue);
        index = str.IndexOf(oldValue, comparison);
    }

    return str;
}

var fruitDictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { { "Apple" , "Fruit" }, { "Orange", "Fruit" }, { "Spinach", "Greens" } };

TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
string data = textRange.Text;

foreach (var kvp in fruitDictionary)
    data = data.Replace(kvp.Key, kvp.Value, StringComparison.InvariantCultureIgnoreCase)

richTextBox2.AppendText(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM