2

I have similar scenario in my project, I have to compare two strings, and Strings are same. But some characters are in capital letters.

string first = "StringCompaRison";
string second = "stringcoMparisoN";
if(first.Equals(second))
{
        Console.WriteLine("Equal ");
}
else
        Console.WriteLine("Not Equal");

For me, output should be equal, am very new to Programming, Which overload to use? Can someone tell me the efficient way to compare?

3 Answers3

3

You're looking for this:

if (first.Equals(second, StringComparison.InvariantCultureIgnoreCase))

String.Equals documentation

StringComparison Enumeration documentation

tnw
  • 13,521
  • 15
  • 70
  • 111
0

There are lot of other ways to do this, When you call a string comparison method such as String.Compare, String.Equals, or String.IndexOf, you should always call an overload that includes a parameter of type StringComparison so that you can specify the type of comparison that the method performs.

Overloads: CurrentCulture, CurrentCultureIgnoreCase, InvariantCulture, InvariantCultureIgnoreCase, Ordinal and OrdinalIgnoreCase

For more information http://msdn.microsoft.com/en-us/library/system.stringcomparison(v=vs.110).aspx

Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance and as your safe default for culture-agnostic string matching,

You can use String.ToUpper, String.ToLower , but this will allocate memory for string.

This is the best way to do,

string first = "StringCompaRison";
string second = "stringcoMparisoN";
if(first.Equals(second,StringComparison.OrdinalIgnoreCase)
{
        Console.WriteLine("Equal ");
}
else
        Console.WriteLine("Not Equal");
Monitor
  • 342
  • 2
  • 13
0

Use String.Compare

bool match = (String.Compare(first, second, true) == 0);
if (match)
{
    Console.WriteLine("Equal");
}
else
{
    Console.WriteLine("Not equal");
}
John Wu
  • 50,556
  • 8
  • 44
  • 80