I’m trying to check a string for key words, and if the word exists, get the value from the dictionary. The problem exists when the key word is a multi-word phrase.
So I have a dictionary:
Dictionary<string, string> d = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
d.Add("keyword1", "D2");
d.Add("keyword2", "D3");
d.Add("keyword3", "D4");
d.Add("keyword4", "D4");
d.Add("keyword5", "D5");
d.Add("key word six", "D6");
And I have a string, which may look like the following but will be a random sentence:
string errormessage = "This is an error regarding Key Word Six";
I’m currently using the following to check the errormessage and see if any words appear in the dictionary:
string code = null;
string theDcode = null;
foreach (string word in errormessage.Split(' '))
{
if (d.TryGetValue(word, out theDcode))
{
code = theDcode;
}
}
The problem is that I can’t search for the string “Key Word Six” since I’m reading the string word by word and the foreach loop sees each word separately. This works great for single word key words. How can I handle checking for a multi word key word?
You could iterate the items in the dictionary instead and check the string for matches.
This would however also give you matches inside of words.
testkeyword1testfor example.EDIT
For possible better performance (untested) you could use a regular expression.
And helper function