简体   繁体   中英

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

By setting the dictionary's comparer to StringComparer.InvariantCultureIgnoreCase , key lookup became culture and case invariant -- ie var a = fruitDictionary["apple"]; and var b = fruitDictionary["ApPlE"] will yield the same results. That said, you perform your replace operation on an instance of StringBuilder which is not related to that. 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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