Beginners Guide to Comparing Strings
One of the great things built in to ASP.Net is the ability to compare two strings with one another, Let’s say you’re in the middle of your coding and you need to check two strings against each other and find out if they’re the same or not. With very little code, you can be up and on your way in no time.
While comparing strings, you also have the added possibility to use or not use case sensitivity. Consider the two strings:
my String
my string
There are 3 parameters to this method:
String 1
String 2
Case Sensitivity
Here’s the general, or most common way it’s used:
System.String.Compare(String1, String2, ignoreCase as Boolean (True/False) as Integer
The boolean parameter at the end can be a little tricky to understand, if you’re new to programming. As you can see, the Boolean value is for ‘ignoreCase’. So, considering the two strings above, if you want to compare the strings, and you don’t care to check for case sensitivity, you will use ‘True’. If you do want to compare them, and take case sensitivity into consideration when checking them, you will use ‘False’.
As you can see, it will return an Integer value. if it returns 0, then the strings are equal to one another. If it returns -1, the strings are NOT equal to one another.
So, to use it in programming, you would do something like this:
Dim String1 as string="my String" Dim String2 as string="my string" ' Ignoring Case: if System.String.Compare(String1,String2,True)=0 then ' put code here if the strings are the same else ' put code here if the strings are NOT the same end if
or:
Dim String1 as string="my String" Dim String2 as string="my string" ' Compare using Case Sensitivity: if System.String.Compare(String1,String2,False)=0 then ' put code here if the strings are the same else ' put code here if the strings are NOT the same end if
Naturally, I’m using the fully qualified namespace here (System.String), but you could, just as easily leave that part off of your code, and Import the System.String namespace.
This is the simplest way to use the String.Compare method. There are actually 9 different overloads for the parameter section, some using Culture/Globalization, CompareMethod (Binary/Text), Length, and different combinations of each of thes. For the whole list, showing the overloads, check out:
http://msdn.microsoft.com/en-us/library/system.string.compare.aspx But as you can see from the title, “ Beginner’s Guide… “, this is where we’re going to stop for this tutorial.
Happy Programming!




09. Feb, 2008 








No comments yet... Be the first to leave a reply!