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
5 Answers
If your strings are at least 5 characters long, then string.Compare should work:
var match = string.Compare(str1, 0, str2, 0, 5) == 0; 1 bool startsWithFoo = "foobar".StartsWith( "foo" ); 1 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.
Try this:
if (str1.Lenght >= 5 && str2.StartsWith(str1.Substring(0, 5)))
{ // Do what you please
} Just use the Substring method to get part of the strings, and verify the length of the strings first unless you are completely sure that they are always at least five characters:
if (str1.Lenght >= 5 && str2.Length >= 5 && str1.Substring(0, 5) == str2.Substring(0, 5)) ... 1