How to determine if string contains specific substring within the first X characters

前端 未结 10 1567
一生所求
一生所求 2020-12-08 09:06

I want to check whether Value1 below contains \"abc\" within the first X characters. How would you check this with an if statement?



        
相关标签:
10条回答
  • 2020-12-08 09:44

    You can also use regular expressions (less readable though)

    string regex = "^.{0,7}abc";
    
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
    string Value1 = "sssddabcgghh";
    
    Console.WriteLine(reg.Match(Value1).Success);
    
    0 讨论(0)
  • 2020-12-08 09:47

    You're close... but use: if (Value1.StartsWith("abc"))

    0 讨论(0)
  • 2020-12-08 09:48

    Or if you need to set the value of found:

    found = Value1.StartsWith("abc")
    

    Edit: Given your edit, I would do something like:

    found = Value1.Substring(0, 5).Contains("abc")
    
    0 讨论(0)
  • 2020-12-08 09:49

    shorter version:

    found = Value1.StartsWith("abc");
    

    sorry, but I am a stickler for 'less' code.


    Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

    public static class StackOverflowExtensions
    {
        public static bool StartsWith(this String val, string findString, int count)
        {
            return val.Substring(0, count).Contains(findString);
        }
    }
    
    0 讨论(0)
  • 2020-12-08 09:50

    This is what you need :

    if (Value1.StartsWith("abc"))
    {
    found = true;
    }
    
    0 讨论(0)
  • 2020-12-08 09:58

    Use IndexOf is easier and high performance.

    int index = Value1.IndexOf("abc");
    bool found = index >= 0 && index < x;
    
    0 讨论(0)
提交回复
热议问题