Reputation: 107
I am checking these strings to see if they contain the word "hi" and returning true if they do. otherwise i am returning false. the string "high up should return false but is returning true. How can i fix this?
public static bool StartHi(string str)
{
if (Regex.IsMatch(str, "hi"))
{
return true;
}
else
return false;
}
static void Main(string[] args)
{
StartHi("hi there"); // -> true
StartHi("hi"); // -> true
StartHi("high up"); // -> false (returns true when i run)
}
Upvotes: 6
Views: 21367
Reputation: 11
This code will return True for "jumps" but not "jump" in sentence.
string sourceText = "The quick brown fox jumps over the lazy white dog.";
string textToCheck = "jump";
if (sourceText.Split(' ').Contains(textToCheck))
{
Console.WriteLine("Word \"" + textToCheck + "\" EXACTLY exists in sentence");
}
else
{
Console.WriteLine("Word \"" + textToCheck + "\" doesn't exist in sentence");
}
Console.ReadLine();
Upvotes: 0
Reputation: 3640
private static bool CheckIfExists(string sourceText, string textToCheck)
{
return sourceText.Split(' ').Contains(textToCheck);
}
Upvotes: 3
Reputation: 32566
Try specifying word boundaries (\b
):
if(Regex.IsMatch(str, @"\bhi\b"))
Upvotes: 21