I have a string "01-02" and I would like to compare it to another string "02-03-1234". Is there a simple way that I can compare if the first five characters of one string are equal to the first five of another string?
Marife
If your strings are at least 5 characters long, then string.Compare
should work:
var match = string.Compare(str1, 0, str2, 0, 5) == 0;
In .NetCore, or .Net framework with System.Memory nuget package:
str1.Length >= 5 && str2.Length >= 5 && str1.AsSpan(0, 5).SequenceEqual(str2.AsSpan(0, 5))
This is extremely heavily optimized, and will be the best performing of all the options here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With