Reputation: 958
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.
Upvotes: 10
Views: 8348
Reputation: 175816
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;
Upvotes: 0
Reputation: 261
here you are
static void Main(string[] args)
{
string word = "Hello my friend how are you ?";
if (word.Substring(0).Contains("Hello"))
{
Console.WriteLine("Match !");
}
}
Upvotes: -2
Reputation: 726629
obviously
Contains
andIndexOf
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) {
...
}
Upvotes: 17