C# 如何确定字符串的前 X 个字符中是否包含特定的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/501026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:48:36  来源:igfitidea点击:

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

c#

提问by

I want to check whether Value1below contains "abc" within the first X characters. How would you check this with an ifstatement?

我想检查Value1下面的前 X 个字符中是否包含“abc”。你将如何用if声明来检查这一点?

var Value1 = "ddabcgghh";

if (Value1.Contains("abc"))
{
    found = true;
}

It could be within the first 3, 4 or 5 characters.

它可以在前 3、4 或 5 个字符内。

回答by olle

if (Value1.StartsWith("abc")) { found = true; }

回答by olle

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

你很接近......但是使用: if (Value1.StartsWith("abc"))

回答by Canavar

This is what you need :

这是你需要的:

if (Value1.StartsWith("abc"))
{
found = true;
}

回答by Jon

Or if you need to set the value of found:

或者,如果您需要设置 found 的值:

found = Value1.StartsWith("abc")

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

编辑:鉴于您的编辑,我会做类似的事情:

found = Value1.Substring(0, 5).Contains("abc")

回答by keithwarren7

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

鉴于提问者的编辑,我实际上会选择接受偏移量的东西,这实际上可能是重载 StartsWith 的扩展方法的好地方

public static class StackOverflowExtensions
{
    public static bool StartsWith(this String val, string findString, int count)
    {
        return val.Substring(0, count).Contains(findString);
    }
}

回答by JaredPar

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.

最好始终明确列出您正在进行的特定比较。String 类可能与所使用的比较类型有些不一致。

回答by Chaowlert Chaisrichalermpol

Use IndexOf is easier and high performance.

使用 IndexOf 更容易且性能更高。

int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;

回答by Pablo Retyk

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

回答by Peter

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

我将使用 IndexOf 方法的重载之一

bool found = Value1.IndexOf("abc", 0, 7) != -1;

回答by Timmy Fuller

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.

您可以通过这种方式检查多个无效值。