字符串替换为字典值
本文关键字:字典 替换 字符串 | 更新日期: 2023-09-27 18:28:19
我在用字典中的值替换字符串中的单词时遇到了一些问题。这是我当前代码的一个小样本:
Dictionary<string, string> replacements = new Dictionary<string, string>()
{
{"ACFT", "AIRCRAFT"},
{"FT", "FEET"},
};
foreach(string s in replacements.Keys)
{
inputBox.Text = inputBox.Text.Replace(s, replacements[s]);
}
当我执行代码时,如果文本框中有ACFT
,它会被AIRCRAFEET
替换,因为它在字符串中看到FT
部分。我需要以某种方式区分这一点,只替换整个单词。
例如,如果框中有ACFT
,它应该将其替换为AIRCRAFT
。如果盒子里有FT
,请将其替换为FEET
。
因此,我的问题是,在替换单词时,如何仅匹配整词?
编辑:我希望能够使用和替换多个单词。
使用if条件。。
foreach(string s in replacements.Keys) {
if(inputBox.Text==s){
inputBox.Text = inputBox.Text.Replace(s, replacements[s]);
}
}
修改问题后更新。。
string str = "ACFT FTT";
Dictionary<string, string> replacements = new Dictionary<string, string>()
{
{"ACFT", "AIRCRAFT"},
{"FT", "FEET"},
};
string[] temp = str.Split(' ');
string newStr = "";
for (int i = 0; i < temp.Length; i++)
{
try
{
temp[i] = temp[i].Replace(temp[i], replacements[temp[i]]);
}
catch (KeyNotFoundException e)
{
// not found..
}
newStr+=temp[i]+" ";
}
Console.WriteLine( newStr);
替换单词时,如何仅匹配整单词?
使用正则表达式(如David Pilkington所建议的)
Dictionary<string, string> replacements = new Dictionary<string, string>()
{
{"ACFT", "AIRCRAFT"},
{"FT", "FEET"},
};
foreach(string s in replacements.Keys)
{
var pattern = "'b" + s + "'b"; // match on word boundaries
inputBox.Text = Regex.Replace(inputBox.Text, pattern, replacements[s]);
}
然而,如果您可以控制设计,我更愿意使用像"{ACFT}"
、"{FT}"
这样的键(它们有明确的边界),所以您可以将它们与String.Replace
一起使用。
我认为您可能需要替换inputText中的最大长度subStr。
int maxLength = 0;
string reStr = "";
foreach (string s in replacements.Keys)
{
if (textBox2.Text.Contains(s))
{
if (maxLength < s.Length)
{
maxLength = s.Length;
reStr = s;
}
}
}
if (reStr != "")
textBox2.Text = textBox2.Text.Replace(reStr, replacements[reStr]);
这个问题是替换整个字符串中子字符串的每个实例。如果您只想替换"ACFT"或"FT"的整个空格分隔实例,则需要使用String.Splitt()来创建一组令牌。
例如:
string tempString = textBox1.Text;
StringBuilder finalString = new StringBuilder();
foreach (string word in tempString.Split(new char[] { ' ' })
{
foreach(string s in replacements.Keys)
{
finalString.Append(word.Replace(s, replacements[s]));
}
}
textBox1.Text = finalString.ToString();
我在这里使用了StringBuilder,因为串联需要每次创建一个新的字符串,而且在长时间内效率非常低。如果您希望有少量的连接要进行,那么您可能可以使用字符串。
请注意,您的设计中有一个小问题——如果您的KeyValuePair的值与字典迭代中稍后出现的键相同,则替换项将被覆盖。
这是一种非常时髦的方法。
首先,您需要使用正则表达式(Regex
),因为它具有匹配单词边界的良好内置功能。
因此,代码的关键行是定义一个Regex
实例:
var regex = new Regex(String.Format(@"'b{0}'b", Regex.Escape("ACFT"));
'b
标记查找单词边界。Regex.Escape
确保,如果您的任何其他密钥具有特殊的Regex
字符,则它们将被转义。
然后你可以这样替换文本:
var replacedtext = regex.Replace("A FT AFT", "FEET");
你会得到replacedtext == "A FEET AFT"
。
现在,这里是时髦的部分。如果您从当前的字典开始,那么您可以定义一个函数来一次性完成所有替换。
这样做:
Func<string, string> funcreplaceall =
replacements
.ToDictionary(
kvp => new Regex(String.Format(@"'b{0}'b", Regex.Escape(kvp.Key))),
kvp => kvp.Value)
.Select(kvp =>
(Func<string, string>)(x => kvp.Key.Replace(x, kvp.Value)))
.Aggregate((f0, f1) => x => f1(f0(x)));
现在你可以这样称呼它:
inputBox.Text = funcreplaceall(inputBox.Text);
不需要循环!
作为一次理智检查,我得到了这个:
funcreplaceall("A ACFT FT RACFT B") == "A AIRCRAFT FEET RACFT B"