字符串替换为字典值

时间:2014-10-30 05:41:24

标签: c# dictionary

我在使用字典中的值替换字符串中的单词时遇到了一些问题。这是我当前代码的一小部分示例:

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

所以我的问题是,在替换单词时如何才能匹配的全部单词?

编辑:我希望能够使用和替换多个单词。

5 个答案:

答案 0 :(得分:1)

  

如何在替换单词时匹配整个单词

使用正则表达式(如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一起使用。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这个问题是您要替换整个字符串中的每个子字符串实例。如果你想要的只是替换整个空格分隔的&#34; ACFT&#34;或者&#34; FT&#34;,您可能希望使用String.Split()来创建一组令牌。

例如:

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的值与字典迭代中稍后出现的键相同,则替换将被覆盖。

答案 3 :(得分:0)

我想你可能想要在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]);

答案 4 :(得分:0)

这是非常时髦的方式。

首先,您需要使用正则表达式(Regex),因为它具有匹配单词边界的良好内置功能。<​​/ p>

因此代码的关键行是定义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"