Strings


From a day-to-day programming standpoint, one of the most important of C#’s data types is string. string defines and supports character strings. In many other programming languages a string is an array of characters. This is not the case with C#. In C#, strings are objects. Thus, string is a reference type. Although string is a built-in data type in C#, a discussion of string needed to wait until classes and objects had been introduced.

Actually, you have been using the string class since Chapter 2. When you create a string literal, you are actually creating a string object. For example, in the statement

 Console.WriteLine("In C#, strings are objects.");

the string “In C#, strings are objects.” is automatically made into a string object by C#. Thus, the use of the string class has been “below the surface” in the preceding programs. In this section you will learn to handle strings explicitly.

Constructing Strings

The easiest way to construct a string is to use a string literal. For example, here str is a string reference variable that is assigned a reference to a string literal:

 string str = "C# strings are powerful.";

In this case, str is initialized to the character sequence “C# strings are powerful.”

You can also create a string from a char array. For example:

 char[] charray = {'t', 'e', 's', 't'}; string str = new string(charray);

Once you have created a string object, you can use it anywhere that a quoted string is allowed. For example, you can use a string object as an argument to WriteLine( ), as shown in this example:

 // Introduce string. using System; class StringDemo {   public static void Main() {     char[] charray = {'A', ' ', 's', 't', 'r', 'i', 'n', 'g', '.' };     string str1 = new string(charray);     string str2 = "Another string.";     Console.WriteLine(str1);     Console.WriteLine(str2);   } }

The output from the program is shown here:

 A string. Another string.

Operating on Strings

The string class contains several methods that operate on strings. Table 7-1 shows a few. The string type also includes the Length property, which contains the length of the string.

Table 7-1: Some Common String Handling Methods

Method

Description

static string Copy(string str)

Returns a copy of str.

int CompareTo(string str)

Returns less than zero if the invoking string is less than str, greater than zero if the invoking string is greater than str, and zero if the strings are equal.

int IndexOf(string str)

Searches the invoking string for the substring specified by str.

Returns the index of the first match, or 1 on failure.

int LastIndexOf(string str)

Searches the invoking string for the substring specified by str.

Returns the index of the last match, or 1 on failure.

string ToLower( )

Returns a lowercase version of the invoking string.

string ToUpper( )

Returns an uppercase version of the invoking string.

To obtain the value of an individual character of a string, you simply use an index. For example:

 string str = "test"; Console.WriteLine(str[0]);

This displays “t”, the first character of “test”. Like arrays, string indexes begin at zero. One important point, however, is that you cannot assign a new value to a character within a string using an index. An index can only be used to obtain a character.

To test two strings for equality, you can use the = = operator. Normally, when the = = operator is applied to object references, it determines if both references refer to the same object. This differs for objects of type string. When the = = is applied to two string references, the contents of the strings, themselves, are compared for equality. The same is true for the != operator: when comparing string objects, the contents of the strings are compared.

Here is a program that demonstrates several string operations:

 // Some string operations. using System; class StrOps {   public static void Main() {     string str1 =       "When it comes to .NET programming, C# is #1.";     string str2 = string.Copy(str1);     string str3 = "C# strings are powerful.";     string strUp, strLow;     int result, idx;     Console.WriteLine("str1: " + str1);     Console.WriteLine("Length of str1: " +                        str1.Length);     // create upper- and lowercase versions of str1     strLow = str1.ToLower();     strUp =  str1.ToUpper();     Console.WriteLine("Lowercase version of str1:\n    " +                       strLow);     Console.WriteLine("Uppercase version of str1:\n    " +                       strUp);     Console.WriteLine();     // display str1, one char at a time.     Console.WriteLine("Display str1, one char at a time.");     for(int i=0; i < str1.Length; i++)       Console.Write(str1[i]);     Console.WriteLine("\n");     // compare strings     if(str1 == str2)       Console.WriteLine("str1 == str2");     else       Console.WriteLine("str1 != str2");     if(str1 == str3)       Console.WriteLine("str1 == str3");     else       Console.WriteLine("str1 != str3");     result = str1.CompareTo(str3);     if(result == 0)       Console.WriteLine("str1 and str3 are equal");     else if(result < 0)       Console.WriteLine("str1 is less than str3");     else       Console.WriteLine("str1 is greater than str3");     Console.WriteLine();     // assign a new string to str2     str2 = "One Two Three One";     // search string     idx = str2.IndexOf("One");     Console.WriteLine("Index of first occurrence of One: " + idx);     idx = str2.LastIndexOf("One");     Console.WriteLine("Index of last occurrence of One: " + idx);   } }

This program generates the following output:

 str1: When it comes to .NET programming, C# is #1. Length of str1: 44 Lowercase version of str1:     when it comes to .net programming, c# is #1. Uppercase version of str1:     WHEN IT COMES TO .NET PROGRAMMING, C# IS #1. Display str1, one char at a time. When it comes to .NET programming, C# is #1. str1 == str2 str1 != str3 str1 is greater than str3 Index of first occurrence of One: 0 Index of last occurrence of One: 14

You can concatenate (join together) two strings using the + operator. For example, this statement:

 string str1 = "One"; string str2 = "Two"; string str3 = "Three"; string str4 = str1 + str2 + str3;

initializes str4 with the string “OneTwoThree”.

One other point: The string keyword is an alias for (that is, maps directly to) the System.String class defined by the .NET Framework class library. Thus, the fields and methods defined by string are those of the System.String class, which includes more than the sampling described here. System.String is examined in detail in Part II.

Arrays of Strings

Like any other data type, strings can be assembled into arrays. For example:

 // Demonstrate string arrays. using System; class StringArrays {   public static void Main() {     string[] str = { "This", "is", "a", "test." };     Console.WriteLine("Original array: ");     for(int i=0; i < str.Length; i++)       Console.Write(str[i] + " ");     Console.WriteLine("\n");     // change a string     str[1] = "was";     str[3] = "test, too!";     Console.WriteLine("Modified array: ");     for(int i=0; i < str.Length; i++)       Console.Write(str[i] + " ");   } }

Here is the output from this program:

 Original array: This is a test. Modified array: This was a test, too!

Here is a more interesting example. The following program displays an integer value using words. For example, the value 19 would display as one nine.

 // Display the digits of an integer using words. using System; class ConvertDigitsToWords {   public static void Main() {     int num;     int nextdigit;     int numdigits;     int[] n = new int[20];     string[] digits = { "zero", "one", "two",                         "three", "four", "five",                         "six", "seven", "eight",                         "nine" };     num = 1908;     Console.WriteLine("Number: " + num);     Console.Write("Number in words: ");     nextdigit = 0;     numdigits = 0;     /* Get individual digits and store in n.        These digits are stored in reverse order. */     do {       nextdigit = num % 10;       n[numdigits] = nextdigit;       numdigits++;       num = num / 10;     } while(num > 0);     numdigits--;     // display words     for( ; numdigits >= 0; numdigits--)       Console.Write(digits[n[numdigits]] + " ");     Console.WriteLine();   } }

The output is shown here:

 Number: 1908 Number in words: one nine zero eight

In the program, the string array digits holds in order the word equivalents of the digits from zero to nine. The program converts an integer into words by first obtaining each digit of the value and storing those digits, in reverse order, in the int array called n. Then, this array is cycled through from back to front. In the process, each integer value in n is used as an index into digits, with the corresponding string being displayed.

Strings Are Immutable

Here is something that might surprise you: The contents of a string object are immutable. That is, once created, the character sequence comprising that string cannot be altered. This restriction allows C# to implement strings more efficiently. Even though this probably sounds like a serious drawback, it isn’t. When you need a string that is a variation on one that already exists, simply create a new string that contains the desired changes. Since unused string objects are automatically garbage-collected, you don’t even need to worry about what happens to the discarded strings.

It must be made clear, however, that string reference variables may, of course, change the object to which they refer. It is just that the contents of a specific string object cannot be changed after it is created.

To fully understand why immutable strings are not a hindrance, we will use another of string’s methods: Substring( ). The Substring( ) method returns a new string that contains a specified portion of the invoking string. Because a new string object is manufactured that contains the substring, the original string is unaltered, and the rule of immutability is still intact. The form of Substring( ) that we will be using is shown here:

 string Substring(int start, int len)

Here, start specifies the beginning index, and len specifies the length of the substring.

Here is a program that demonstrates Substring( ) and the principle of immutable strings:

 // Use Substring(). using System; class SubStr {   public static void Main() {     string orgstr = "C# makes strings easy.";     // construct a substring     string substr = orgstr.Substring(5, 12);     Console.WriteLine("orgstr: " + orgstr);     Console.WriteLine("substr: " + substr);   } }

Here is the output from the program:

 orgstr: C# makes strings easy. substr: kes strings

As you can see, the original string orgstr is unchanged and substr contains the substring.

One more point: Although the immutability of string objects is not usually a restriction or hindrance, there may be times when it would be beneficial to be able to modify a string. To allow this, C# offers a class called StringBuilder, which is in the System.Text namespace. It creates string objects that can be changed. For most purposes, however, you will want to use string, not StringBuilder.

Strings Can Be Used in switch Statements

A string can be used to control a switch statement. It is the only non-integer type that can be used in the switch. The fact that strings can be used in switch statements makes it possible to handle some formerly tedious situations quite easily. For example, the following program displays the digit equivalent of the words “one,” “two,” and “three”:

 // A string can control a switch statement. using System; class StringSwitch {   public static void Main() {     string[] strs = { "one", "two", "three", "two", "one" };     foreach(string s in strs) {       switch(s) {         case "one":           Console.Write(1);           break;         case "two":           Console.Write(2);           break;         case "three":           Console.Write(3);           break;       }     }     Console.WriteLine();   } }

The output is shown here:

 12321




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net