C # - efficiently check if a string contains a string at a specific position (something like regionMatches)

For example, I might have a string "Hello world!"

and I want to check if the substring starting at position 6 (based on 0) "world"

is true in this case.

Something like "Hello world!".Substring(6).StartsWith("world", StringComparison.Ordinal)

would do it, but it has to do with heap allocation, which should be unnecessary for something like this.

(In my case, I don't want a border error if the line starting at position 6 is too short for comparison - I just need false. However, this is easy to code, so solutions that give a border error are also welcome.)

In Java, "regionMatches" can be used to achieve this effect (with bounds error), but I cannot find an equivalent in C #.

Just to be preemptive - obviously, Contains

and IndexOf

are bad decisions because they do unnecessary searches. (You know someone will post this!)

If all else fails, quickly copy my own function to do this - basically I'm wondering if there is a built in that I missed.

+3


source to share


3 answers


obvious Contains

and IndexOf

bad decisions because they do unnecessary searches

Actually, it is not: there is an overload IndexOf

that allows you to control how far it has to go in search of a match. If you told it to stay at one particular index, it would do exactly what you want it to achieve.

Here's a 3-factor overload IndexOf

you could use. Passing the target length for a parameter count

does not allow IndexOf

any other positions to be considered:



var big = "Hello world!";
var small = "world";
if (big.IndexOf(small, 6, small.Length) == 6) {
    ...
}

      

Demo version

+11


source


Or manually



int i = 0;
if (str.Length >= 6 + toFind.Length) {
    for (i = 0; i < toFind.Length; i++)
        if (str[i + 6] != toFind[i])
            break;
}
bool ok = i == toFind.Length;

      

0


source


Here you

static void Main(string[] args)
    {
        string word = "Hello my friend how are you ?";

        if (word.Substring(0).Contains("Hello"))
        {
            Console.WriteLine("Match !");
        }

    }

      

-2


source







All Articles