Добавил:
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

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.

Lead-in

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

!The .NET Framework Has Methods to Compare 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

11

 

 

 

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.

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.

For Your Information

You should cover the

String.Split method because it is used in the lab.

The Split Method

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

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