There are several ways to compare strings in C #. The first is the plain old ==, etc. works well if the software does not move to another location. Another way to do this is the CompareTo (), which has several overloads and allows you to compare entire strings or substrings.
string a1 = "About C,C++ and C#";
string a2=a1.Substring(0,5) ; // About
if (a2.CompareTo("About")==0)
 // do something
Here we will see how you can use the Compare instance methods and methods related to string type. Normally you need to compare the methods for the classification of the algorithms and to verify if a string is before or after the other in an ASCII sort.
Program that uses Compare (C#)
using System;
class Program
{
static void Main()
{
string a = "a"; // 1
string b = "b"; // 2
int c = string.Compare(a, b);
Console.WriteLine(c);
c = string.CompareOrdinal(b, a);
Console.WriteLine(c);
c = a.CompareTo(b);
Console.WriteLine(c);
c = b.CompareTo(a);
Console.WriteLine(c);
}
}
Output of the program
1 (This means a is smaller than b)
1 (This means b is smaller than a)
-1
1
0 comments:
Post a Comment