Comparing strings

The next two examples demonstrate various methods for comparing strings. To understand how one string can be "greater than" or "less than" another string, consider the process of alphabetizing a series of last names. The reader would, no doubt, place "Jones" before "Smith", because the first letter of "Jones" comes before the first letter of "Smith" in the alphabet. The alphabet is more than just a set of 26 lettersit is an ordered list of characters in which each letter occurs in a specific position. For example, Z is more than just a letter of the alphabet; Z is specifically the twenty-sixth letter of the alphabet.

Computers can order characters alphabetically because the characters are represented internally as Unicode numeric codes. When comparing two strings, C# simply compares the numeric codes of the characters in the strings.

Class string provides several ways to compare strings. The application in Fig. 16.3 demonstrates the use of method Equals, method CompareTo and the equality operator (==).

Figure 16.3. string test to determine equality.

 1 // Fig. 16.3: StringCompare.cs
 2 // Comparing strings
 3 using System;
 5 class StringCompare
 6 {
 7 public static void Main()
 8 {
 9 string string1 = "hello";
10 string string2 = "good bye";
11 string string3 = "Happy Birthday";
12 string string4 = "happy birthday";
14 // output values of four strings
15 Console.WriteLine( "string1 = "" + string1 + """ +
16 "
string2 = "" + string2 + """ +
17 "
string3 = "" + string3 + """ +
18 "
string4 = "" + string4 + ""
" );
20 // test for equality using Equals method
21 if ( string1.Equals( "hello" ) )
22 Console.WriteLine( "string1 equals "hello"" );
23 else
24 Console.WriteLine( "string1 does not equal "hello"" );
26 // test for equality with ==
27 if ( string1 == "hello" )
28 Console.WriteLine( "string1 equals "hello"" );
29 else
30 Console.WriteLine( "string1 does not equal "hello"" );
32 // test for equality comparing case
33 if ( string.Equals( string3, string4 ) ) // static method
34 Console.WriteLine( "string3 equals string4" );
35 else
36 Console.WriteLine( "string3 does not equal string4" );
37 38 // test CompareTo 39 Console.WriteLine ( " string1.CompareTo( string2 ) is " + 40 string1.CompareTo( string2 ) + " " + 41 "string2.CompareTo( string1 ) is " + 42 string2.CompareTo( string1 ) + " " + 43 "string1.CompareTo( string1 ) is " + 44 string1.CompareTo( string1 ) + " " + 45 "string3.CompareTo( string4 ) is " + 46 string3.CompareTo( string4 ) + " " + 47 "string4.CompareTo( string3 ) is " + 48 string4.CompareTo( string3 ) + " " ); 49 } // end method Main 50 } // end class StringCompare
string1 = "hello"
string2 = "good bye"
string3 = "Happy Birthday"
string4 = "happy birthday"

string1 equals "hello"
string1 equals "hello"
string3 does not equal string4

string1.CompareTo( string2 ) is 1
string2.CompareTo( string1 ) is -1
string1.CompareTo( string1 ) is 0
string3.CompareTo( string4 ) is 1
string4.CompareTo( string3 ) is -1

The condition in the if statement (line 21) uses string method Equals to compare string1 and literal string "hello" to determine whether they are equal. Method Equals (inherited from object and overridden in string) tests any two objects for equality (i.e., checks whether the objects contain identical contents). The method returns true if the objects are equal and false otherwise. In this instance, the preceding condition returns true, because string1 references string literal object "hello". Method Equals uses a lexicographical comparisonthe integer Unicode values that represent each character in each string are compared. A comparison of the string "hello" with the string "HELLO" would return false, because the numeric representations of lowercase letters are different from the numeric representations of corresponding uppercase letters.

The condition in line 27 uses the equality operator (==) to compare string string1 with the literal string "hello" for equality. In C#, the equality operator also uses a lexicographical comparison to compare two strings. Thus, the condition in the if statement evaluates to true, because the values of string1 and "hello" are equal.

We present the test for string equality between string3 and string4 (line 33) to illustrate that comparisons are indeed case sensitive. Here, static method Equals is used to compare the values of two strings. "Happy Birthday" does not equal "happy birthday", so the condition of the if statement fails, and the message "string3 does not equal string4" is output (line 36).

Lines 4048 use string method CompareTo to compare strings. Method CompareTo returns 0 if the strings are equal, a negative value if the string that invokes CompareTo is less than the string that is passed as an argument and a positive value if the string that invokes CompareTo is greater than the string that is passed as an argument. Method CompareTo uses a lexicographical comparison.

Notice that CompareTo considers string3 to be larger than string4. The only difference between these two strings is that string3 contains two uppercase letters in positions where string4 contains lowercase letters.

The application in Fig. 16.4 shows how to test whether a string instance begins or ends with a given string. Method StartsWith determines whether a string instance starts with the string text passed to it as an argument. Method EndsWith determines whether a string instance ends with the string text passed to it as an argument. Class stringStartEnd's Main method defines an array of strings (called strings), which contains "started", "starting", "ended" and "ending". The remainder of method Main tests the elements of the array to determine whether they start or end with a particular set of characters.

Figure 16.4. StartsWith and EndsWith methods.

 1 // Fig. 16.4: StringStartEnd.cs
 2 // Demonstrating StartsWith and EndsWith methods.
 3 using System;
 5 class StringStartEnd
 6 {
 7 public static void Main()
 8 {
 9 string[] strings =
10 { "started", "starting", "ended", "ending" };
12 // test every string to see if it starts with "st"
13 for ( int i = 0; i < strings.Length; i++ )
14 if ( strings[ i ].StartsWith( "st" ) )
15 Console.WriteLine( """ + strings[ i ] + """ +
16 " starts with "st"" );
18 Console.WriteLine( "" );
20 // test every string to see if it ends with "ed"
21 for ( int i = 0; i < strings.Length; i++ )
22 if ( strings[ i ].EndsWith( "ed" ) )
23 Console.WriteLine( """ + strings[ i ] + """ +
24 " ends with "ed"" );
26 Console.WriteLine( "" );
27 } // end method Main
28 } // end class StringStartEnd
"started" starts with "st"
"starting" starts with "st"

"started" ends with "ed"
"ended" ends with "ed"

Line 14 uses method StartsWith, which takes a string argument. The condition in the if statement determines whether the string at index i of the array starts with the characters "st". If so, the method returns TRue, and strings[i] is output along with a message.

Line 22 uses method EndsWith, which also takes a string argument. The condition in the if statement determines whether the string at index i of the array ends with the characters "ed". If so, the method returns TRue, and strings[i] is displayed along with a message.



    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look


    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2


    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures



    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types


    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: