16.5 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, 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 letters—it’s 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; it’s specifically the twenty-sixth letter of the alphabet. Computers can order characters alphabetically because they’re represented internally as numeric codes and those codes are ordered according to the alphabet so, for example, 'a' is less than 'b'—see Appendix C.

Comparing strings with Equals, CompareTo and the Equality Operator (==)

Class string provides several ways to compare strings. Figure 16.3 demonstrates methods Equals and CompareTo and the equality operator (==).

Fig. 16.3 Comparing strings.

Alternate View

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

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 line 21 uses string method Equals to compare string1 and literal string "hello" (the argument) to determine whether they’re equal. Method Equals (inherited from object and overridden in string) tests two strings for equality (i.e., checks whether the strings have identical contents). The method returns true if the objects are equal and false otherwise. In this case, the condition returns true, because string1 references string literal object "hello". Method Equals uses word sorting rules that do not depend on your system’s currently selected culture. Comparing "hello" with "HELLO" would return false, because the lowercase letters are different from the corresponding uppercase letters.

The condition in line 31 uses class string’s overloaded equality operator (==) to compare string string1 with the literal string "hello" for equality. In C#, the equality operator also compares the contents of two strings. Thus, the condition in the if statement evaluates to true, because the values of string1 and "hello" are equal.

Line 41 tests whether string3 and string4 are equal 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 fails, and the message "string3 does not equal string4" is output (line 47).

Lines 51–60 use string method CompareTo to compare strings. The method returns 0 if the strings are equal, a negative value if the string that invokes CompareTo is less than the string that’s passed as an argument and a positive value if the string that invokes CompareTo is greater than the string that’s passed as an argument.

Notice that CompareTo considers string3 to be greater than string4. The only difference between these two strings is that string3 contains two uppercase letters in positions where string4 contains lowercase letters. The method uses sorting rules that are case and culture sensitive.

Determining Whether a String Begins or Ends with a Specified String

Figure 16.4 tests whether a string begins or ends with a given string. Method StartsWith determines whether a string starts with the string passed to the method as an argument. Method EndsWith determines whether a string ends with the string passed to the method as an argument.

Fig. 16.4 Demonstrating StartsWith and EndsWith methods.

Alternate View

 1    // Fig. 16.4: StringStartEnd.cs
 2    // Demonstrating StartsWith and EndsWith methods.
 3    using System;
 4
 5    class StringStartEnd
 6    {
 7       static void Main()
 8       {
 9          string[] strings = {"started", "starting", "ended", "ending"};
10
11          // test every string to see if it starts with "st"
12          foreach (var element in strings)
13          {
14             if (element.StartsWith("st"))
15             {
16                Console.WriteLine($""{element}" starts with "st"");
17             }
18          }
19
20          Console.WriteLine();
21
22          // test every string to see if it ends with "ed"
23          foreach (var element in strings)
24          {
25             if (element.EndsWith("ed"))
26             {
27                Console.WriteLine($""{element}" ends with "ed"");
28             }
29          }
30
31          Console.WriteLine();
32       }
33    }

"started" starts with "st"
"starting" starts with "st"

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

Line 9 defines an array of strings, which contains "started", "starting", "ended" and "ending". Line 14 uses method StartsWith, which takes a string argument. The condition in the if statement determines whether the current element starts with the characters "st". If so, the method returns true, and the element is displayed along with a message.

Line 25 uses method EndsWith to determine whether the current element ends with the characters "ed". If so, the method returns true, and the element is displayed along with a message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset