string Constructors

Class string provides eight constructors for initializing strings in various ways. Figure 16.1 demonstrates the use of three of the constructors.

Figure 16.1. string constructors.

1 // Fig. 16.1: StringConstructor.cs 2 // Demonstrating string class constructors. 3 using System; 4 5 class StringConstructor 6 { 7 public static void Main() 8 { 9 string originalString, string1, string2, 10 string3, string4; 11 char[] characterArray = 12 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; 13 14 // string initialization 15 originalString = "Welcome to C# programming!"; 16 string1 = originalString; 17 string2 = new string( characterArray ); 18 string3 = new string( characterArray, 6, 3 ); 19 string4 = new string( 'C', 5 ); 20 21 Console.WriteLine( "string1 = " + """ + string1 + "" " + 22 "string2 = " + """ + string2 + "" " + 23 "string3 = " + """ + string3 + "" " + 24 "string4 = " + """ + string4 + "" " ); 25 } // end method Main 26 } // end class StringConstructor  

string1 = "Welcome to C# programming!" string2 = "birth day" string3 = "day" string4 = "CCCCC"

Lines 910 declare the strings originalString, string1, string2, string3 and string4. Lines 1112 allocate the char array characterArray, which contains nine characters. Line 15 assigns string literal "Welcome to C# programming!" to string reference originalString. Line 16 sets string1 to reference the same string literal.

Line 17 assigns to string2 a new string, using the string constructor that takes a character array as an argument. The new string contains a copy of the characters in array characterArray.

Software Engineering Observation 16 1

In most cases, it is not necessary to make a copy of an existing string. All strings are immutabletheir character contents cannot be changed after they are created. Also, if there are one or more references to a string (or any object for that matter), the object cannot be reclaimed by the garbage collector.

Line 18 assigns to string3 a new string, using the string constructor that takes a char array and two int arguments. The second argument specifies the starting index position (the offset) from which characters in the array are to be copied. The third argument specifies the number of characters (the count) to be copied from the specified starting position in the array. The new string contains a copy of the specified characters in the array. If the specified offset or count indicates that the program should access an element outside the bounds of the character array, an ArgumentOutOfRangeException is thrown.

Line 19 assigns to string4 a new string, using the string constructor that takes as arguments a character and an int specifying the number of times to repeat that character in the string.

string Indexer, Length Property and CopyTo Method

Категории