0

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 a a 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?

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I'm dense. Sorry for the inane question, but thank you for the prompt answer. My eyes must be tired.
Glad I could help! Don't worry, it happens to all of us :)
0

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

1 Comment

Note it is somewhat pointless to provide exactly the same answer 40 minutes later... Especially with worse formatting. Unless you plan to vastly improve the answer to make it superior to the older one I'd recommend deleting it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.