0
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

1 Answer 1

7

By setting the dictionary's comparer to StringComparer.InvariantCultureIgnoreCase, key lookup became culture and case invariant -- i.e. 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.