Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string contains a specific word C#

Tags:

string

c#

regex

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)
    }
like image 501
user3121357 Avatar asked Aug 04 '14 01:08

user3121357


People also ask

How do you check if a string contains a word in C?

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.

How do I check if a string contains a specific word?

Use the Contains() method to check if a string contains a word or not.

How do you check if a certain character is in a string C?

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.

How do you check if a word has a letter in C?

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.


1 Answers

Try specifying word boundaries (\b):

if(Regex.IsMatch(str, @"\bhi\b"))
like image 134
AlexD Avatar answered Sep 28 '22 10:09

AlexD