Click here to Skip to main content
16,002,232 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,
I ran accross another bug in my code.
my code snippet is something line this.

C#
string MyLine = "The Fast Cars";
if(Myline.Contains("Fast"))
{
//do something.
}


in this case the "if" statement is true.

Now if the string,
MyLine = "The Fastest Cars"; or
MyLine = "The Fastest, Cars"; or
MyLine = "The xxFastest, Cars";


Then the above "if" condition will pass.
Can this be avoided.
Posted
Updated 21-Jul-10 18:12pm
v3

Use this method:
C#
public static bool ContainsWord(string line, string word)
{
    return Regex.IsMatch(line, @"\b" + word + @"\b");
}
 
Share this answer
 
How is it true ?

Anyhow assuming you fix the code, you'd have to put a space either side of the word you search for, to search for the whole word only.
 
Share this answer
 
Comments
asjadazeez 21-Jul-10 23:58pm    
Ah sorry typing mistake the if statement should be MyLine.Contains("Fast")
Toli Cuturicu 25-Jul-10 9:13am    
Reason for my vote of 2
Not so, comma, dot and other characters are word separators too.
Another way - you could split your string on spaces (i.e. blanks) into an array and then go through that array to check the exact string you are looking for.
 
Share this answer
 
Comments
Toli Cuturicu 25-Jul-10 9:14am    
Reason for my vote of 2
Not so, comma, dot and other characters are word separators too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900