C# find exact-match in string

前端 未结 4 1541
生来不讨喜
生来不讨喜 2021-02-07 22:18

How can I search for an exact match in a string? For example, If I had a string with this text:

label
label:
labels

And I search for label, I only want

相关标签:
4条回答
  • 2021-02-07 22:58

    You can try to split the string (in this case the right separator can be the space but it depends by the case) and after you can use the equals method to see if there's the match e.g.:

    private Boolean findString(String baseString,String strinfToFind, String separator)
    {                
        foreach (String str in baseString.Split(separator.ToCharArray()))
        {
            if(str.Equals(strinfToFind))
            {
                return true;
            }
        }
        return false;
    }
    

    And the use can be

    findString("Label label Labels:", "label", " ");
    
    0 讨论(0)
  • 2021-02-07 23:05

    It seems you've got a delimiter (crlf) between the words so you could include the delimiter as part of the search string.

    If not then I'd go with Liviu's suggestion.

    0 讨论(0)
  • 2021-02-07 23:06

    You could try a LINQ version:

    string str = "Hello1 Hello Hello2";
    string another = "Hello";
    string retVal = str.Split(" \n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                       .First( p => p .Equals(another));
    
    0 讨论(0)
  • 2021-02-07 23:08

    You can use a regular expression like this:

    bool contains = Regex.IsMatch("Hello1 Hello2", @"(^|\s)Hello(\s|$)"); // yields false
    bool contains = Regex.IsMatch("Hello1 Hello", @"(^|\s)Hello(\s|$)"); // yields true
    

    The \b is a word boundary check, and used like above it will be able to match whole words only.

    I think the regex version should be faster than Linq.

    Reference

    0 讨论(0)
提交回复
热议问题