1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Programming Tutorial - About Strings and Chars

By David Bolton, About.com

6 of 10

Comparing Strings in C#

There are several ways you can compare strings in C#. First is the plain old ==, etc which works fine so long as your software doesn't move to another locale. Another way of doing this is the CompareTo() method which has several overloads and lets you compare entire strings or sub-strings.
string a1 = "About C,C++ and C#";
string a2=a1.Substring(0,5) ; // About
if (a2.CompareTo("About")==0)
  // do something
This comparison returns 0 for a match, -1 or 1 depending upon the lexicographical ordering of the two strings. Lexicographical usually means writing dictionaries but here it means how the letters are sorted. It's easy enough sorting English without the accents, graves, circumflexes, cedillas, umlauts etc that occur in other languages but when you have to take those into account it needs a bit more thought. Don't think your software will be used elsewhere? What if you decide to put it on a website?

Or there is the string static method compare. Rember static means that the method used belongs to the class, not an instance of the class. So you call string.Compare()

    string a1 = "About C,C++ and C#";
    if (string.Compare("About",a1)==0)
        Console.WriteLine("It Matches!") ;
    else
        Console.WriteLine("It doesn't Match!") ;

Other String Functions

C#, or more accurately .NET comes with a rich set of string functions. Need upper or lower case?
string ToLower()
string ToUpper()
These are also static methods that return a string. It's important to remember that strings are immutable so these return a new string and the original string remains unchanged.

On the next page - Yet More String Functions

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Comparing Strings in C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.