Recently, I have started working on a project and lots of time I have to deal with strings. Comparing string tokens for equality and then calling the related operation. Sometimes strings do not need to be strictly equal (L.H.S == R.H.S).
What are the best way to compare Strings?
Choosing a correct way to compare strings based on comparing condition is a tradeoff between String.Compare() and String.Contains() function.
public static int Compare(string string1, string string2)
Compares two string objects and returns an integer value, based on its relative position in the sort order (source https://docs.microsoft.com/en-us/dotnet/api/system.string.compare?view=netframework-4.8).
public bool Contains(string string1)
Compares two strings and returns a boolean value indicating if the string contains a substring (source https://docs.microsoft.com/en-us/dotnet/api/system.string.contains?view=netframework-4.8).
Let's take an example to better understand the difference between these two functions.
I have a fruit list(basket of fruits) and I have decided to create fruit salad using only apples.
Well, this will give me apples from the basket. Now I want pineapple also from the basket.
This will work, But what if my list contains 1000 records and I have to look for some 10 different types of apples. Obviously, looping over 10 condition is not a solution. So here, String.Contains() function comes into picture.
But be careful with what you choose! You cannot use String.Contains() if a string is someway not a substring of another string.
Top comments (2)
There are usually more conditions to factor in like case and culture. How would that affect your best method for comparison?
Definitely there is some case where regex are the only solution when the input string is not none but we know the pattern of input string. But the conditions I have explained are the ones I am facing with my recent project. I am dealing with a string token where, some string token are completely unique and for some tokens first few characters do repeat and they are bit of same type. For such case they are ideal solution.