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

45 c#

我想检查Value1下面是否在前X个字符中包含"abc".你会如何用if声明来检查?

var Value1 = "ddabcgghh";

if (Value1.Contains("abc"))
{
    found = true;
}
Run Code Online (Sandbox Code Playgroud)

它可以在前3,4或5个字符内.

Jon*_*Jon 50

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

found = Value1.StartsWith("abc")
Run Code Online (Sandbox Code Playgroud)

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

found = Value1.Substring(0, 5).Contains("abc")
Run Code Online (Sandbox Code Playgroud)


小智 18

我会使用IndexOf方法的一个重载

bool found = Value1.IndexOf("abc", 0, 7) != -1;
Run Code Online (Sandbox Code Playgroud)


kei*_*en7 11

较短的版本:

found = Value1.StartsWith("abc");
Run Code Online (Sandbox Code Playgroud)

对不起,但我是"少"代码的坚持者.


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

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


oll*_*lle 8

if (Value1.StartsWith("abc")) { found = true; }
Run Code Online (Sandbox Code Playgroud)


Cha*_*pol 7

使用IndexOf更容易,性能更高.

int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;
Run Code Online (Sandbox Code Playgroud)