[英]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);
它可以正常工作,但是如果輸入格式不正確,它將無法正常工作。 例如,在Apple上,輸出為Fruit,但在Apple上,仍顯示為apple
通過將字典的比較器設置為StringComparer.InvariantCultureIgnoreCase
,關鍵字查找將變為區域性var a = fruitDictionary["apple"];
區分大小寫-例如, var a = fruitDictionary["apple"];
並且var b = fruitDictionary["ApPlE"]
將產生相同的結果。 就是說,您對與此無關的StringBuilder
實例執行替換操作。 StringBuilder.Replace
和String.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.