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

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

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)

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

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *