Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
173
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 7: Strings, Arrays, and Collections

v

 

 

 

Module Strategy

Use the following strategy to present this module:

!Strings

Discuss how to work with strings in the Microsoft .NET Framework, including common operations, such as parsing, formatting, manipulating, and comparing strings.

!Terminology – Collections

Define the term collection as it is used in this module and identify where collections are found in the .NET Framework. Be sure that students understand that the term collection is used in its broader sense: to describe a group of items.

!.NET Framework Arrays

Introduce the System.Array class as the base class of all array types that contains methods for creating, manipulating, searching, and sorting arrays.

Discuss features of arrays that are specific to C#. Explain the role of the

IEnumerable and IEnumerator interfaces in System.Array and System.Collections classes.

Use the Sorting and Enumerating an Array demonstration to show how to sort and enumerate an array.

!.NET Framework Collections

Briefly introduce some commonly used classes in the System.Collections namespace.

Discuss the IList interface with regards to classes that represent an ordered collection of objects that can be individually indexed. Use the ArrayList demonstration to reinforce this concept.

Discuss the IDictionary interface and the classes that it implements. Use the Hashtable demonstration to show how to use the IDictionary interface.

Provide guidelines to help students distinguish between collections and arrays, and explain when collections are used.

Discuss runtime casting for type safety and the effects of runtime casting, and boxing and unboxing on performance. Discuss techniques for handling boxing and unboxing to optimize performance.

Module 7: Strings, Arrays, and Collections

1

 

 

 

Overview

Topic Objective

To provide an overview of the module topics and objectives.

Lead-in

In this module, you will learn about some of the key classes in the .NET Framework class library.

!Strings

!Terminology – Collections

!.NET Framework Arrays

!.NET Framework Collections

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this module, you will learn about some of the key classes in the Microsoft®

.NET Framework class library. Specifically, you will learn how to work with strings, arrays, collections, and enumerators.

After completing this module, you will be able to:

!Parse, format, manipulate, and compare strings.

!Use the classes in the System.Array and System.Collections namespaces.

!Improve the type safety and performance of collections by using specialized collections and class-specific code.

2Module 7: Strings, Arrays, and Collections

" Strings

Topic Objective

To introduce the topics in the section.

Lead-in

In this section, you will learn how to work with strings in the .NET Framework.

!Parse

!Format

!Format Examples

!Changing Case

!Compare

!Trim and Pad

!Split and Join

!StringBuilder

!C# Specifics

!Regular Expressions

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In the C# language, string is an alias for System.String in the .NET

Framework. The System.String type represents a string of Unicode characters.

Working with strings is an everyday task in software development, and includes operations, such as parsing, formatting, manipulating, and comparing strings.

The String object is immutable. Therefore, every time you use one of the methods in the System.String class, you create a new string object. When you want to perform repeated modifications to a string, the overhead that is associated with creating a new String object can be costly. As an alternative, you can use the System.Text.StringBuilder class to modify a string without creating a new object.

In this section, you will learn how to work with strings in the .NET Framework.

Module 7: Strings, Arrays, and Collections

3

 

 

 

Parse

Topic Objective

To explain how the Parse method is used to convert numeric strings to a .NET Framework numeric base type.

Lead-in

The Parse method converts a string that represents a

.NET Framework numeric base type to an actual .NET Framework numeric base type.

! Parse Method Converts a Numeric String to a Numeric

string MyString = "12345"; string MyString = "12345";

int MyInt = int.Parse(MyString); int MyInt = int.Parse(MyString); MyInt++;

MyInt++;

Console.WriteLine(MyInt);

Console.WriteLine(MyInt);

// The output to the console is "12346". // The output to the console is "12346".

!To Ignore Commas, Use the NumberStyles.AllowThousands Flag

string MyString = "123,456"; string MyString = "123,456"; int MyInt = int.Parse(MyString, int MyInt = int.Parse(MyString,

System.Globalization.NumberStyles.AllowThousands);

System.Globalization.NumberStyles.AllowThousands);

Console.WriteLine(MyInt);

Console.WriteLine(MyInt);

// The output to the console is "123456". // The output to the console is "123456".

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The Parse method converts a string that represents a .NET Framework numeric base type to an actual .NET Framework numeric base type.

The Parse method takes a combination of up to three parameters, as follows:

!The string to be converted

!One or more values from the System.Globalization.NumberStyles enumeration

!A NumberFormatInfo class

Because the Parse method assumes that all string input represents a base-10 value, non-base-10 values are not parsable. The Parse method also does not parse strings that represent the values NaN (Not A Number), PositiveInfinity, or NegativeInfinity of the Single and Double classes because they are not real numbers.

The following code example converts a string to an int value, increments that value, and displays the result:

string MyString = "12345";

int MyInt = int.Parse(MyString); MyInt++; Console.WriteLine(MyInt);

// The output to the console is "12346".

4Module 7: Strings, Arrays, and Collections

Handling Nonnumeric Characters

The NumberStyles enumeration is useful if you have a string that contains nonnumeric characters that you want to convert into a .NET Framework numeric base type. You must use this enumeration to parse a string with a currency symbol, decimal point, exponent, parentheses, and so on.

For example, a string that contains a comma cannot be converted to an int value by using the Parse method unless you pass the

System.Globalization.NumberStyles enumeration.

Incorrect Way to Parse a String with Nonnumeric Characters

The following code example is invalid and raises an exception. It illustrates the incorrect way to parse a string that contains nonnumeric characters.

string MyString = "123,456";

// the following line raises a System.Format exception int MyInt = int.Parse(MyString); Console.WriteLine(MyInt);

Correct Way to Parse a String with Nonnumeric Characters

When you apply the System.Globalization.NumberStyles enumeration with the AllowThousands flag, the Parse method ignores the comma that raised the exception in the preceding example.

The following code example uses the same string as the preceding example but does not raise an exception.

string MyString = "123,456"; int MyInt = int.Parse(MyString,

System.Globalization.NumberStyles.AllowThousands);

Console.WriteLine(MyInt);

// The output to the console is "123456"

Module 7: Strings, Arrays, and Collections

5

 

 

 

Format

Topic Objective

To explain how to use format strings, or specifiers, to format the appearance of your application.

Lead-in

The .NET Framework provides several format strings that you can use to format the appearance of strings that derive from other objects.

!Format Strings Are Used in Methods That Create String Representations of a .NET Framework Data Type

#To display $100.00 to the console on computers on which U.S. English is the current culture

int MyInt = 100; int MyInt = 100;

string MyString = MyInt.ToString("C"); string MyString = MyInt.ToString("C"); Console.WriteLine(MyString); Console.WriteLine(MyString);

# Alternatively

int MyInt = 100; int MyInt = 100;

Console.WriteLine("{0:C}", MyInt); Console.WriteLine("{0:C}", MyInt);

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The .NET Framework provides several format strings, or specifiers, that you can use to format the appearance of strings that derive from other objects.

There are several advantages to converting base data types to strings before displaying them to users. Strings are easily displayed and can be appended to the messages and dialog boxes of your application. You can also use format specifiers to display the same numeric value in scientific format, monetary format, hexadecimal format, and so on.

When to Use Format Strings

You can use format specifiers in situations where your application stores information in a format that is designed for use by the application, and not by the user. For example, a business application may keep track of the current date and time in a DateTime object to log when transactions are completed. The DateTime object stores information in which the user is not necessarily interested, such as the number of milliseconds that have elapsed since the creation of the object.

You can also use format specifiers to display only information that is of interest to the user, such as the date and hour of the transaction. Additionally, you can dynamically modify strings that are created by using format specifiers to represent monetary, date, and time conventions for the current culture. For example, your application can display the date and time in the notation that is specific to the user’s current culture.

6Module 7: Strings, Arrays, and Collections

Methods Used with Format Strings

Format strings are used with any method that creates a string representation of a

.NET Framework data type, such as Int32, Int64, Single, Double, Enumeration, DateTime, and so on. Format strings are also used with

Console.Writeline, String.Format, and several methods in the System.IO namespace.

Additionally, every base data type contains a ToString method that returns a string representation of the data type’s value and accepts a string format specifier. You can control the layout and design of strings that are created by any of these methods by using one of several format strings defined by the

.NET Framework.

Using the ToString Method

The ToString method is useful if you want to convert one of the standard .NET

Framework data types to a string that represents that type in some other format.

For example, if you have an integer value of 100 that you want to represent to the user as a currency value, you can easily use the ToString method and the currency format string ("C") to produce a string of "$100.00". The original value that is contained in the data type is not converted, but a new string is returned that represents the resulting value. This new string cannot be used for calculation until it is converted back to a .NET base data type. The original value, however, can be calculated at any time.

Note Computers that do not have U.S. English specified as the current culture will display whatever currency notation is used by the current culture.

In the following code example, the ToString method displays the value of 100 as a currency-formatted string in a console window:

int MyInt = 100;

string MyString = MyInt.ToString("C"); Console.WriteLine(MyString);

The preceding code displays $100.00 to the console on a computer on which

U.S. English is the current culture.

Using Console.Writeline

The Console.WriteLine method also accepts a format string specifier as an argument and can produce the same value as the preceding example. Console.Writeline accepts string format specifiers in the form, where the characters inside the curly brackets specify the formatting to apply to the variable.

The following code example uses the Console.WriteLine method to format the value of MyInt to a currency value.

int MyInt = 100; Console.WriteLine("{0:C}", MyInt);

In the preceding example, the 0 character specifies the variable or value on which to apply formatting. In this example, it is the first and only variable. The characters that follow the colon are interpreted as string format specifiers.

Module 7: Strings, Arrays, and Collections

7

 

 

 

Format Examples

Topic Objective

To provide examples of format strings that return common numeric string types.

Lead-in

Let’s look at some examples of format strings that return the value of MyString in the currency and date time formats.

! Currency Format

# C - $XX,XXX.XX

int MyInt = 12345; int MyInt = 12345;

string MyString = MyInt.ToString("C" ); string MyString = MyInt.ToString("C" );

// In the U.S. English culture: "$12,345.00" // In the U.S. English culture: "$12,345.00"

! Date Time Format

# D - dd MMMM yyyy

# d - MM/dd/yyyy

DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0); DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0); string MyString = MyDate.ToString( "d" );

string MyString = MyDate.ToString( "d" ); // In the U.S. English culture: "1/10/2000" // In the U.S. English culture: "1/10/2000"

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The standard numeric, picture numeric, date and time, and enumeration format strings are described in detail in the .NET Framework Software Development Kit (SDK). This topic provides examples of these format strings.

The following examples show the use of the format string that returns the value of MyInt in the currency format:

int MyInt = 12345;

string MyString = MyInt.ToString( "C" );

//In the U.S. English culture, MyString has the value:

//"$12,345.00".

The following table lists some format characters for standard patterns that are used to format DateTime types.

 

Associated

Example Format Pattern

Format Character

Property/Description

(en-US)

 

 

 

d

ShortDate Pattern

D

LongDatePattern

f

Full date and time (long date

 

and short time)

F

FullDateTimePattern (long

 

date and long time)

MM/dd/yyyy

Dd MMMM yyyy Dd MMMM yyyy HH:mm

Dd MMMM yyyy HH:mm:ss

8Module 7: Strings, Arrays, and Collections

The following example shows the use of the format string that returns the value of MyDate in the short date pattern format:

DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0);

string MyString = MyDate.ToString( "d" );

//In the U.S. English culture, MyString has the value:

//"1/10/2000".

Соседние файлы в папке c#