Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 25 OTHER TOPICS

Overview

In this chapter, I’ll cover a number of other topics that are important in using C# but that don’t fit neatly into one of the other chapters. These include string handling, nullable types, the Main method, documentation comments, and nested types.

Strings

0s and 1s are fine for internal computation, but for human-readable input and output, we need strings of characters. The BCL provides a number of classes that make string handling easy.

The C# predefined type string represents the .NET class System.String. The most important things to know about strings are the following:

Strings are arrays of Unicode characters.

Strings are immutable—they cannot be changed.

The string type has many useful string-manipulation members, including those that allow you to determine their length, change their case, concatenate strings, and perform many other useful tasks. Table 25-1 shows some of the most useful members.

Table 25-1. Useful Members of the string Type

Member

Type

Meaning

Length

Property

Returns the length of the string

Concat

Static method

Returns a string that is the concatenation of its argument strings

Contains

Method

Returns a bool value indicating whether the argument is a substring

 

 

of the object string

Format

Static method

Returns a formatted string

Insert

Method

Takes as parameters a string and a position and creates and returns a

 

 

new copy of the object string, with the parameter string inserted at

 

 

the given position.

Remove

Method

Returns a copy of the object string in which a substring has been

 

 

removed

Replace

Method

Returns a copy of the object string in which a substring has been

 

 

replaced

Substring

Method

Retrieves a substring from the object string

ToUpper

Method

Returns a copy of the object string in which the alphabetic characters

 

 

are all uppercase

ToLower

Method

Returns a copy of the object string in which the alphabetic characters

 

 

are all lowercase

 

 

 

664

CHAPTER 25 OTHER TOPICS

The names of many of the methods in Table 25-1 sound as if they are changing the string object. Actually, they’re not changing the strings but returning new copies. For a string, any “change” allocates a new immutable string.

For example, the following code declares and initializes a string called s. The first WriteLine statement calls the ToUpper method on s, which returns a copy of the string in all uppercase. The last line prints out the value of s, showing that it is unchanged.

string s = "Hi there.";

 

 

Console.WriteLine("{0}", s.ToUpper());

// Print uppercase copy

Console.WriteLine("{0}", s);

// String is unchanged

This code produces the following output:

 

 

 

 

 

HI THERE.

 

 

Hi there.

 

 

 

 

 

665

CHAPTER 25 OTHER TOPICS

Using Class StringBuilder

The StringBuilder class helps you dynamically and efficiently produce strings without too many copies being made.

The StringBuilder class is a member of the BCL, in namespace System.Text.

A StringBuilder object is a mutable array of Unicode characters.

For example, the following code declares and initializes a StringBuilder and prints its resulting string value. The fourth line changes the actual object by replacing part of the internal array of characters. Now when you print its string value by implicitly calling ToString, you can see that, unlike an object of type string, the StringBuilder object has actually been changed.

using System.Text;

 

 

StringBuilder sb

= new StringBuilder("Hi there.");

Console.WriteLine("{0}", sb);

// Print string

sb.Replace("Hi",

"Hello");

//

Replace a substring

Console.WriteLine("{0}", sb);

//

Print changed string

This code produces the following output:

Hi there.

Hello there.

When a StringBuilder object is created based on a given string, the class allocates a buffer longer than the actual current string length. As long as the changes made to the string can fit in the buffer, no new memory is allocated. If changes to the string require more space than is available in the buffer, a new, larger buffer is allocated, and the characters are copied to it. Like the original buffer, this new buffer also has extra space.

To get the string corresponding to the StringBuilder content, you simply call its ToString method.

666

CHAPTER 25 OTHER TOPICS

Formatting Numeric Strings

Throughout the text, the sample code has used the WriteLine method to display values. Each time, it used the simple substitution marker consisting of curly braces surrounding an integer. Many times, however, you’ll want to present the output of a text string in a format more appropriate than just a plain number. For example, you might want to display a value as currency or as a fixed-point value with a certain number of decimal places. You can do these things by using format strings.

For example, the following code consists of two statements that print out the value 500. The first line prints out the number without any additional formatting. In the second line, the format string specifies that the number should be formatted as currency.

Console.WriteLine("The value: {0}." , 500);

// Print out number

Console.WriteLine("The value: {0:C}.", 500);

// Format as currency

 

 

Format as currency

 

 

This code produces the following output:

 

 

 

 

 

The value: 500.

 

 

The value: $500.00.

 

 

 

 

 

The difference between the two statements is that the format item includes additional information in the form of a format specifier. The syntax for a format specifier consists of three fields inside the set of curly braces: the index, the alignment specifier, and the format specifier. Figure 25-1 shows the syntax.

Figure 25-1. Syntax for a format item

The first thing in the format item is the index. As you well know by now, the index specifies which item from the list following the format string should be formatted. The index is required, and the numbering of the list items starts at 0.

667

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]