CopyPastehas never been so tasty!

Compare function to compare strings in C#

by anonymous

  • 0
  • 0
  • 0
82 views

Orignal Source:http://codingvilla.com/compare-function-compare-strings-csharp-single-article-607.aspx

Compare Function:

 

The Compare function in C# compares the two strings and it will return an Integer and it shows the linguistic relationship between these strings. It takes two strings as parameter.

 

The syntax of compare function is

 

int string.Compare(string s1,string s2)

 

It will return an integer that may be zero, less than zero or greater than zero. It will return zero if the first string is equals to the second string. And it will return integer less than zero if first string is less than from second string. And it will return integer greater than zero if first string is greater from second string.

 

Compare function to compare strings:

 

To understand that how we can use compare method let us consider this example in this example we are using compare method and pass 2 strings as parameter and get their results. If the first string is equals to the second string the answer will be zero and if first string is less than from second string the answer will be -1 and if first string is greater from second string the answer will be 1.

 

To demonstrate make a console application and write the following code

 

 

Code:

 

 

classString_Compare_method

    {

staticvoid Main(string[] args)

        {

              Try

{

int result;

result = String.Compare("bbc", "abc");

Console.WriteLine("String.Compare(\"bbc\", \"abc\") = " + result);

result = String.Compare("abc", "bbc");

Console.WriteLine("String.Compare(\"abc\", \"bbc\") = " + result);

result = String.Compare("bbc", "bbc");

Console.WriteLine("String.Compare(\"bbc\", \"bbc\") = " + result);

result = String.Compare("bbc", "BBC", true);

Console.WriteLine("String.Compare(\"bbc\", \"BBC\", true) = " + result);

result = String.Compare("bbc", "BBC", false);

Console.WriteLine("String.Compare(\"bbc\", \"BBC\", false) = " + result);

Console.ReadLine();

 

        }

catch(Exceptionexce)

{

 

Console.WriteLine(exce);

 

}

 

}

 

    }

Add A Comment: