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

前端 未结 10 1568
一生所求
一生所求 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 10:02

    A more explicit version is

    found = Value1.StartsWith("abc", StringComparison.Ordinal);
    

    It's best to always explicitly list the particular comparison you are doing. The String class can be somewhat inconsistent with the type of comparisons that are used.

    0 讨论(0)
  • 2020-12-08 10:03

    Adding on from the answer below i have created this method:

        public static bool ContainsInvalidStrings(IList<string> invalidStrings,string stringToCheck)
        {
    
            foreach (string invalidString in invalidStrings)
            {
                var index = stringToCheck.IndexOf(invalidString, StringComparison.InvariantCultureIgnoreCase);
                if (index != -1)
                {
                    return true;
                }
            }
            return false;
        }
    

    it can be used like this:

                var unsupportedTypes = new List<string>()
            {
                "POINT Empty",
                "MULTIPOINT",
                "MULTILINESTRING",
                "MULTIPOLYGON",
                "GEOMETRYCOLLECTION",
                "CIRCULARSTRING",
                "COMPOUNDCURVE",
                "CURVEPOLYGON",
                "MULTICURVE",
                "TRIANGLE",
                "TIN",
                "POLYHEDRALSURFACE"
            };
    
    
                bool hasInvalidValues =   ContainsInvalidStrings(unsupportedTypes,possibleWKT);
    

    you can check for multiple invalid values this way.

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

    I would use one of the of the overloads of the IndexOf method

    bool found = Value1.IndexOf("abc", 0, 7) != -1;
    
    0 讨论(0)
提交回复
热议问题