Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, I might have the string "Hello world!", and I want to check if a substring starting at position 6 (0-based) is "world" - in this case true.

Something like "Hello world!".Substring(6).StartsWith("world", StringComparison.Ordinal) would do it, but it involves a heap allocation which ought to be unnecessary for something like this.

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

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

Just to pre-empt - obviously Contains and IndexOf are bad solutions because they do an unnecessary search. (You know someone will post this!)

If all else fails, it's quick to code my own function for this - mainly I'm wondering if there is a built-in one that I've missed.

like image 323
entheh Avatar asked Jan 07 '15 17:01

entheh


1 Answers

obviously Contains and IndexOf are bad solutions because they do an unnecessary search

Actually, that's not true: there is an overload of IndexOf that keeps you in control of how far it should go in search of the match. If you tell it to stay at one specific index, it would do exactly what you want to achieve.

Here is the three-argument overload of IndexOf that you could use. Passing the length of the target for the count parameter would prevent IndexOf from considering any other positions:

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

Demo.

like image 140
Sergey Kalinichenko Avatar answered Oct 26 '22 10:10

Sergey Kalinichenko