Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare part of a string?

Tags:

c#

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

like image 999
Marife Avatar asked May 15 '11 20:05

Marife


2 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;
like image 85
Chaquotay Avatar answered Sep 23 '22 09:09

Chaquotay


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.

like image 21
Yair Halberstadt Avatar answered Sep 20 '22 09:09

Yair Halberstadt