简体   繁体   中英

C# Replacing String in Foreach loop

I'm trying to replace text. I'm using a dictionary for the task.

public static string cleanString(this String str) {

    Dictionary<string, string> dict = new Dictionary<string,string>();
    dict.Add("JR", "Junior");
    dict.Add("SR", "Senior");

    foreach (KeyValuePair<string,string> d in dict) {
        if (str.BlindContains(p.Key)) {
            str = str.BlindReplace(str, p.Value);
        }
    }

    return str;
}

BlindContains and BlindReplace just ignore the case of the replacement (and BC ensures the string is not part of another word):

public static bool BlindContains(this String str, string toCheck)
{
    if (Regex.IsMatch(str, @"\b" + toCheck + @"\b", RegexOptions.IgnoreCase))
        return str.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0;
    return false;
}
public static string BlindReplace(this String str, string oldStr, string newStr)
{
    return Regex.Replace(str, oldStr, newStr, RegexOptions.IgnoreCase);
}

The problem

If I call my method on aa string, the following occurs:

string mystring = "The jr. is less than the sr."
mystring.cleanString()

returns "Junior"

However, when I print

Console.WriteLine(Regex.Replace(mystring, "jr.", "junior", Regex.IgnoreCase));

I get the output: "The junior is less than the sr."

Why does the loop compromise the task?

You should be passing the key in your dictionary (Which contains the text to search for), rather than the actual string you are searching in.

It should be:

str = str.BlindReplace(p.Key, p.Value);

As opposed to:

str = str.BlindReplace(str, p.Value);

You are currently replacing your string with the value "Junior" because you specified your string as the text to search for. (Which will make it replace the entire string instead of just the keyword)

In cleanString implementation I think you made an error in your call to BlindReplace. Instead of:

str = str.BlindReplace(str, p.Value);

I believe you should have called:

str = str.BlindReplace(d.Key, d.Value);

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