String.Compare() or String.Contains(), best way to compare strings

Ravina Deogadkar - Mar 15 '20 - - Dev Community

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).

Alt Text

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.

Alt Text

I have a fruit list(basket of fruits) and I have decided to create fruit salad using only apples.

Alt Text

Well, this will give me apples from the basket. Now I want pineapple also from the basket.

Alt Text

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.

Alt Text

But be careful with what you choose! You cannot use String.Contains() if a string is someway not a substring of another string.

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .