检查字符串是否包含特定的c#单词

本文关键字:单词 包含特 字符串 是否 检查 | 更新日期: 2023-09-27 18:16:25

我正在检查这些字符串,看看它们是否包含单词"hi",如果包含则返回true。否则返回false。字符串"high up "应该返回false,但返回的是true。我怎样才能解决这个问题?

    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)
    }

检查字符串是否包含特定的c#单词

尝试指定字边界('b):

if(Regex.IsMatch(str, @"'bhi'b"))
private static bool CheckIfExists(string sourceText, string textToCheck)
    {
        return sourceText.Split(' ').Contains(textToCheck);
    }

此代码将为"跳转"返回True;但不是"跳";在句子。

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();