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)
}
The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.
Use the Contains() method to check if a string contains a word or not.
The strchr() function returns a pointer to the first occurrence of c that is converted to a character in string. The function returns NULL if the specified character is not found.
In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0. The isalpha() function is defined in <ctype.
Try specifying word boundaries (\b
):
if(Regex.IsMatch(str, @"\bhi\b"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With