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.
source to share
obvious
Contains
andIndexOf
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) {
...
}
source to share