Tải bản đầy đủ (.pdf) (70 trang)

Tài liệu Module 7: Strings, Arrays, and Collections pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (955.59 KB, 70 trang )

Module 7: Strings,
Arrays, and Collections
Contents
Overview
Strings
Terminology – Collections

1
2
20

.NET Framework Arrays

21

.NET Framework Collections

39

Lab 7: Working with Strings, Enumerators,
and Collections
57
Review

63


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,


logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
 2001-2002 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.


Module 7: Strings, Arrays, and Collections

iii

Instructor Notes
Presentation:
120 Minutes

After completing this module, students will be able to:
!

Parse, format, manipulate, and compare strings.


!

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

!

Lab:
60 Minutes

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

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.

Required Materials
To teach this module, you need the Microsoft® PowerPoint® file 2349B_07.ppt.

Preparation Tasks
To prepare for this module, you should:
!

Read all of the materials for this module.

!

Practice the demonstrations.


!

Complete the lab.


iv

Module 7: Strings, Arrays, and Collections

Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.

Sorting and Enumerating an Array
In this demonstration, you will show students how to sort and enumerate an
array.
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.1. In addition, the code for the
individual demonstration is provided in the student notes.

ArrayList
In this demonstration, you will show students how ArrayList implements the
IList interface by using an array whose size is dynamically increased as
required.
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.2. In addition, the code for the
individual demonstration is provided in the student notes.

Hashtable
In this demonstration, you will show students how to create a hash table that is

used for searches.
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.3. In addition, the code for the
individual demonstration is provided in the student notes.
In all of the preceding demonstrations, use the debugger to step through the
code while you point out features.


Module 7: Strings, Arrays, and Collections

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.

v



Module 7: Strings, Arrays, and Collections


1

Overview
Topic Objective

To provide an overview of
the module topics and
objectives.

!
!

.NET Framework Arrays

!

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

Terminology – Collections

!

Lead-in

Strings

.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.


2

Module 7: Strings, Arrays, and Collections

" Strings
Topic Objective

To introduce the topics in
the section.


!

Parse

Lead-in

!

Format

!

Format Examples

!

Changing Case

!

Compare

!

Trim and Pad

!

Split and Join


!

StringBuilder

!

C# Specifics

!

Regular Expressions

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

*****************************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.

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".

Lead-in


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

!

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".


4

Module 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.


6

Module 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.

!

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"

Lead-in

Let’s look at some examples

of format strings that return
the value of MyString in the
currency and date time
formats.

!

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.
Format Character

Associated
Property/Description

Example Format Pattern
(en-US)

d

ShortDate Pattern

MM/dd/yyyy

D

LongDatePattern

Dd MMMM yyyy

f

Full date and time (long date
and short time)


Dd MMMM yyyy

FullDateTimePattern (long
date and long time)

Dd MMMM yyyy

F

HH:mm
HH:mm:ss


8

Module 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".


Module 7: Strings, Arrays, and Collections

9


Changing Case
Topic Objective

To explain how to use the
String.ToUpper and
String.ToLower methods to
change the case of a string.

Lead-in

You can easily change the
case of a string by using the
String.ToUpper and
String.ToLower methods.

!

You Can Easily Change the Case of a String
#

String.ToUpper – converts to upper case

string MyString = "hello world!";
string MyString = "hello world!";
// outputs: HELLO WORLD!
// outputs: HELLO WORLD!
Console.WriteLine(MyString.ToUpper());
Console.WriteLine(MyString.ToUpper());
#


String.ToLower – converts to lower case

string MyString = "HELLO WORLD!";
string MyString = "HELLO WORLD!";
// outputs: hello world!
// outputs: hello world!
Console.WriteLine(MyString.ToLower());
Console.WriteLine(MyString.ToLower());

*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can easily change the case of a string by using the two methods that are
described in the following table.
Method Name

Use

String.ToUpper

Converts all characters in a string to uppercase.

String.ToLower

Converts all characters in a string to lowercase.

String.ToUpper and String.ToLower provide an override that accepts a
culture.
The String.ToUpper method changes all of the characters in a string to
uppercase.
The following code example converts the string "hello world!" from
lowercase to uppercase:

string MyString = "hello world!";
Console.WriteLine(MyString.ToUpper());

The preceding example displays HELLO WORLD! to the console.
The String.ToLower method is similar to the String.ToUpper method, but it
converts all of the characters in a string to lowercase.
The following code example converts the string "HELLO WORLD!" to lowercase.
string MyString = "HELLO WORLD!";
Console.WriteLine(MyString.ToLower());

The preceding example displays hello world! to the console.


10

Module 7: Strings, Arrays, and Collections

Compare
Topic Objective

To introduce some of the
value-comparison methods
that are used to compare
the values of strings.

!

The .NET Framework Has Methods to Compare Strings
#


Lead-in

The .NET Framework
provides several valuecomparison methods to
compare the values of
strings.

For example, the Compare method compares the
current string object to another string or object, returning:
- Negative if first string is less than second string
- 0 if the two strings are equal
- Positive if first string is greater than second string

string MyString = "Hello World!";
string MyString = "Hello World!";
Console.WriteLine(
Console.WriteLine(
String.Compare(MyString,"Hello World!"));
String.Compare(MyString,"Hello World!"));
// outputs: 0
// outputs: 0

*****************************ILLEGAL FOR NON-TRAINER USE******************************
The .NET Framework provides several methods to compare the values of
strings. The following table describes some of the value-comparison methods.
Method Name

Use

String.Compare


Compares the values of two strings. Returns an integer value.

String.StartsWith

Determines if a string begins with the string passed. Returns a
boolean value.

String.IndexOf

Returns the index of the first occurrence of a String, or one or
more characters, within this instance.

For more information about value comparison methods and for a complete list
of these methods, see “Comparing Strings” in the .NET Framework SDK
documentation.
For example, the String.Compare method provides a thorough way to compare
the current string object to another string or object. You can use this function to
compare two strings or substrings of two strings.
Additionally, overloads are provided that regard or disregard case and cultural
variance.


Module 7: Strings, Arrays, and Collections

The following table shows the three integer values that are returned by the
Compare(string strA, string strB) method.
Value Type

Condition


A negative integer

strA is less than strB

0

strA equals strB

A positive integer

strA is greater than strB

The following code example uses the Compare method to determine whether
two strings are the same.
string MyString = "Hello World!";
Console.WriteLine(String.Compare(MyString, "Hello World!"));

The preceding example displays 0 to the console.

11


12

Module 7: Strings, Arrays, and Collections

Trim and Pad
Topic Objective


To explain how to use
methods of the
System.String class to trim
and pad strings.

Lead-in

You can remove or extend
the spaces around strings
by using methods of the
System.String class.

!

Trim Methods Remove Spaces

string MyString = " Big ";
string MyString = " Big ";
Console.WriteLine("Hello{0}World!", MyString );
Console.WriteLine("Hello{0}World!", MyString );
string TrimString = MyString.Trim();
string TrimString = MyString.Trim();
Console.WriteLine("Hello{0}World!", TrimString );
Console.WriteLine("Hello{0}World!", TrimString );
// outputs the following lines to the console:
// outputs the following lines to the console:
//Hello Big World!
//Hello Big World!
//HelloBigWorld!
//HelloBigWorld!

!

Pad Methods Expand a Specific Number of Characters

string MyString = "Hello World!";
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));
Console.WriteLine(MyString.PadLeft(20, '-'));
// outputs the following line to the console:
// outputs the following line to the console:
//--------Hello World! to the console.
//--------Hello World! to the console.

*****************************ILLEGAL FOR NON-TRAINER USE******************************
When you want to remove or extend the spaces around strings, the
System.String class provides methods for trimming and padding strings.

Trimming
When you are parsing a sentence into individual words, you might have white
spaces on either end of a word. You can use one of the trim methods in the
System.String class to remove any number of spaces from the beginning or end
of the string.
The following table describes two of the available trim methods.
Method Name

Use

String.Trim

Removes white spaces from the beginning and end of a string.


String.Remove

Removes a specified number of characters from a specified index
position in a string.

For example, you can easily remove white spaces from both ends of a string by
using the String.Trim method, as shown in the following code example.
string MyString = " Big ";
Console.WriteLine("Hello{0}World!", MyString );
string TrimString = MyString.Trim();
Console.WriteLine("Hello{0}World!", TrimString );

This code outputs the following lines to the console:
Hello Big World!
HelloBigWorld!

For a complete list of trim methods in the System.String class, see “Trimming
and Removing Characters” in the .NET Framework SDK documentation.


Module 7: Strings, Arrays, and Collections

13

Padding
System.String also provides methods that you can use to create a new version
of an existing string that is expanded by a specific number of characters.
The following table describes the available pad methods.
Method Name


Use

String.PadLeft

Right aligns and pads a string, so its rightmost character is a
specified distance from the beginning of the string.

String.PadRight

Left aligns and pads a string, so its rightmost character is a
specified distance from the beginning of the string.

For example, the String.PadLeft method creates a new string that moves an
existing string to the right, so its last character is a specified number of spaces
from the first index of the string. White spaces are inserted if you do not use an
override that allows you to specify your own custom padding character.
The following code example uses the PadLeft method to create a new string
with a total length of 20 spaces.
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));

This example displays the following text to the console.
--------Hello World!


14

Module 7: Strings, Arrays, and Collections


Split and Join
Topic Objective

To explain how to use the
Split and Join methods to
break up and concatenate
strings.

!

#

Lead-in

The System.String class
provides the Split method to
break up strings and the
Join method to concatenate
strings.

Split Method Is Used to Break Up a String Into an Array of
Substrings

#

String is broken at positions indicated by the specified separator
characters parameter
If the separator parameter is null, the whitespace characters are
assumed to be the separator


string Line = "Hello World";
string Line = "Hello World";
string[] Words = Line.Split(null);
string[] Words = Line.Split(null);
// Words[0] = "Hello" and Words[1] = "World"
// Words[0] = "Hello" and Words[1] = "World"
!

Join Method Is Used to Concatenate Strings
#

A specified separator string is placed between each element of a
string array

*****************************ILLEGAL FOR NON-TRAINER USE******************************
The System.String class provides the Split method to break up strings and the
Join method to concatenate strings.

The Split Method
For Your Information

You should cover the
String.Split method
because it is used in the lab.

You use the Split method to break up a string instance into an array of
substrings at the positions that are specified by separator characters. If separator
characters are omitted, that is to say, if the parameter is null, the whitespace
characters are assumed to be the separator. If the separator is a zero-length
string, a single-element array that contains the entire expression string is

returned.
The following example shows how to break up a string into a string array of
words:
string Line = "Hello World";
string[] Words = Line.Split(null);
// Words[0] = "Hello" and Words[1] = "World"

The Join Method
You use the Join method to concatenate a specified separator string between
each element of a specified String array, which yields a single concatenated
string. If the separator is omitted, that is to say null, the space character (" ")
is used. If the separator is a zero-length string (""), all of the items in the list
are concatenated with no delimiters.


Module 7: Strings, Arrays, and Collections

15

StringBuilder
Topic Objective

To explain how to use the
StringBuilder method to
modify a string without
creating a new object.

Lead-in

When you want to perform

repeated modifications to a
string, use the
System.Text.StringBuilder
class to modify a string
without creating a new
object.

!

The String Object is Immutable

!

System.Text.StringBuilder – Allows You to Modify a
String Without Creating a New Object

StringBuilder MyStringBuilder = new StringBuilder("Hello");
StringBuilder MyStringBuilder = new StringBuilder("Hello");
!

You Can Specify the Maximum Number of Characters

// MyStringBuilder can hold a maximum of 25 characters
// MyStringBuilder can hold a maximum of 25 characters
StringBuilder MyStringBuilder =
StringBuilder MyStringBuilder =
new StringBuilder("Hello World!", 25);
new StringBuilder("Hello World!", 25);
!


Methods Include:
#

Append, AppendFormat, Insert, Remove,
and Replace

*****************************ILLEGAL FOR NON-TRAINER USE******************************
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.

Creating a StringBuilder Object
You can create a new instance of the StringBuilder object by initializing your
variable with one of the overloaded constructor methods, as shown in the
following code example:
StringBuilder MyStringBuilder = new StringBuilder("Hello");

Although the StringBuilder object is a dynamic object that allows you to
expand the number of characters in the string that it encapsulates, you can
specify a value for the maximum number of characters that it can hold. This
value is called the capacity of the object and must not be confused with the
length of the string that the current StringBuilder object holds. Any attempt to
expand the StringBuilder class beyond the maximum range causes an
ArgumentOutOfRangeException to be thrown.
The following code example specifies that the MyStringBuilder object can be
expanded to a maximum of 25 spaces.
StringBuilder MyStringBuilder =

new StringBuilder("Hello World!", 25);


16

Module 7: Strings, Arrays, and Collections

StringBuilder Methods
The following table describes the methods that you can use to modify the
contents of the StringBuilder object.
Method Name

Use

StringBuilder.Append

Appends information to the end of the current
StringBuilder object.

StringBuilder.AppendFormat

Replaces zero or more format specifications with
the appropriately formatted value of an object.

StringBuilder.Insert

Inserts a string or object into the specified index of
the current StringBuilder object.

StringBuilder.Remove


Removes a specified number of indexes from the
current StringBuilder object.

StringBuilder.Replace

Replaces a specified index or character with the
passed character.


Module 7: Strings, Arrays, and Collections

17

C# Specifics
Topic Objective

To explain what the string
type is in the .NET
Framework and to describe
the functions of the +, [ ],
and != operators, and @quoting.

Lead-in

The string type represents
a string of Unicode
characters; string is an
alias for System.String in
the .NET Framework.


!

C# string Type Is a String of Unicode Characters
#
#

#

Alias for System.String
Equality operators (== and !=) compare the values of string objects,
not references
The + operator concatenates strings

string a = "\u0068ello ";
string a = "\u0068ello ";
string b = "world";
string b = "world";
Console.WriteLine( a + b == "hello world" );//True
Console.WriteLine( a + b == "hello world" );//True
#

The [ ] operator accesses individual characters of a string

char x = "test"[2]; // x = 's';
char x = "test"[2]; // x = 's';
#

With @-quoting, escape sequences are not processed


@"c:\Docs\Source\a.txt"
@"c:\Docs\Source\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"

*****************************ILLEGAL FOR NON-TRAINER USE******************************
The string type represents a string of Unicode characters; string is an alias for
System.String in the .NET Framework.
Although string is a reference type, the equality (==) operator and the
inequality (!=) operator are defined to compare the values of string objects, not
the references. Comparing the values of string objects makes testing for string
equality more intuitive, as in the following example:
string a = "hello";
string b = "hello";
Console.WriteLine( a == b );

// output: True -- same value

The + operator concatenates strings, as in the following example:
string a = "good " + "morning";

The [ ] operator accesses individual characters of a string, as in the following
example:
char x = "test"[2];

// x = 's';

String literals are of type string and can be written in two forms: quoted and
@-quoted. Quoted string literals are enclosed in quotation marks ("), as in the
following example:

"good morning"

// a string literal

Quoted string literals can also contain any character literal, including escape
sequences, as in the following example:
string a = "\\\u0066\n";

// backslash, letter f, new line


18

Module 7: Strings, Arrays, and Collections

@-quoted string literals start with @ and are enclosed in quotation marks, as in
the following example:
@"good morning"

// a string literal

The advantage of using @-quoted string literals is that escape sequences are not
processed. This makes it easy to write a fully qualified file name, as in the
following example:
@"c:\Docs\Source\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"

To include a quoted phrase in an @-quoted string, use two pairs of double
quotation marks, as in the following example:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.


The following code example uses the C# features that are discussed in this
topic:
using System;
class test
{
public static void Main( String[] args )
{
string a = "\u0068ello ";
string b = "world";
Console.WriteLine( a + b );
Console.WriteLine( a + b == "hello world" );
}
}

The preceding code example displays the following output to the console:
hello world
True


Module 7: Strings, Arrays, and Collections

19

Regular Expressions
Topic Objective

To briefly describe how
regular expressions can be
used in the .NET

Framework.

!

Regular Expressions – Powerful Text Processing

!

Pattern-Matching Notation Allows You to:

Lead-in

Regular expressions allow
you to quickly parse large
amounts of text in order to
find specific character
patterns; to extract, edit,
replace, or delete text
substrings; and to add the
extracted strings to a
collection to generate a
report.

#
#

Extract, edit, replace, or delete text substrings

#


!

Find specific character patterns
Add the extracted strings to a collection to generate
a report

Designed to be Compatible With Perl 5

*****************************ILLEGAL FOR NON-TRAINER USE******************************
This topic provides a brief
summary of regular
expressions. Do not spend
much time on this slide, but
encourage students to refer
to the .NET Framework
SDK, especially for details
about using the regular
expression classes.

Regular expressions provide a powerful, flexible, and efficient method to
process text. The extensive pattern-matching notation of regular expressions
allows you to quickly parse large amounts of text to find specific character
patterns; to extract, edit, replace, or delete text substrings; and to add the
extracted strings to a collection in order to generate a report.
For many applications that deal with strings, such as HTML processing, log file
parsing, and HTTP header parsing, regular expressions are an essential tool.
The .NET Framework regular expressions incorporate the most popular features
of other regular expression implementations, such as those used in Perl and
awk. Designed to be compatible with Perl 5 regular expressions, .NET
Framework regular expressions include features that are not yet available in

other implementations, such as right-to-left matching and dynamic compilation.
The .NET Framework regular expression classes are part of the .NET
Framework class library and can be used with any language or tool that targets
the common language runtime, including ASP.NET and Microsoft
Visual Studio® .NET.
A detailed explanation of how to use the regular expression classes is beyond
the scope of this course. For more information about using regular expression
classes, see the .NET Framework SDK documentation.


×