简体   繁体   English

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

[英]Checking if a string contains a specific word C#

I am checking these strings to see if they contain the word "hi" and returning true if they do.我正在检查这些字符串以查看它们是否包含单词“hi”,如果包含则返回 true。 otherwise i am returning false.否则我返回错误。 the string "high up should return false but is returning true. How can i fix this?字符串“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)
    }

尝试指定单词边界\\b ):

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

This code will return True for "jumps" but not "jump" in sentence.此代码将为“跳跃”返回 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM