Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

The \rescape character simply brings the cursor to the beginning of the line, and hence in the above statements the word " Two" is printed at the beginning of the line. The \rescape character is often used together with \nto form a new line (see Figure 8-6):

string str1 = "Line 1\n\r";

string str2 = "Line 2\n\r";

Console.Write(str1);

Console.Write(str2);

C 2008 Programmers Reference - изображение 136

Figure 8-6

By default, when you use the \nto insert a new line, the cursor is automatically returned to the beginning of the line. However, some legacy applications still require you to insert newline and carriage return characters in strings.

The following table summarizes the different escape sequences you have seen in this section:

Sequence Purpose
\n New line
\r Carriage return
\r\n Carriage return; New line
\" Quotation marks
\\ Backslash character
\t Tab

In C#, strings can also be @-quoted. Earlier, you saw that to include special characters (such as double-quote, backslash, and so on) in a string you need to use the backslash character to turn off its special meaning:

string path="C:\\Windows";

You can actually use the @character, and prefix the string with it, like this:

string path=@"C:\Windows";

Using the @character makes your string easier to read. Basically, the compiler treats strings that are prefixed with the @ character verbatim — that is, it just accepts all the characters in the string (inside the quotes). To better appreciate this, consider the following example where a string containing an XML snippet is split across multiple lines (with each line ending with a carriage return):

string XML = @"

";

Console.WriteLine(XML);

Figure 8-7 shows the output. The WriteLine()method prints out the line verbatim.

Figure 87 To illustrate the use of the character on a doublequoted string - фото 137

Figure 8-7

To illustrate the use of the @ character on a double-quoted string, the following:

string quotation =

"\"I don't necessarily agree with everything I say.\" Marshall McLuhan";

Console.WriteLine(quotation);

can be rewritten as:

string quotation =

@"""I don't necessarily agree with everything I say."" Marshall McLuhan";

Console.WriteLine(quotation);

Escape Code for Unicode

C# supports the use of escape code to represent Unicode characters. The four-digit escape code format is: \udddd. For example, the following statement prints out the £ symbol:

string symbol = "\u00A3";

Console.WriteLine(symbol);

For more information on Unicode, check out http://unicode.org/Public/UNIDATA/NamesList.txt.

String Manipulations

Often, once your values are stored in string variables, you need to perform a wide variety of operations on them, such as comparing the values of two strings, inserting and deleting strings from an existing string, concatenating multiple strings, and so on. The Stringclass in the .NET Framework provides a host of methods for manipulating strings, some of the important ones of which are explained in the following sections.

You can find out about all of the Stringclass methods at www.msdn.com.

Testing for Equality

Even though string is a reference type, you will use the ==and !=operators to compare the value of two strings (not their references).

Consider the following three string variables:

string str1 = "This is a string";

string str2 = "This is a ";

str2 += "string";

string str3 = str2;

The following statements test the equality of the values contained in each variable:

Console.WriteLine(str1 == str2); //---True---

Console.WriteLine(str1 == str3); //---True---

Console.WriteLine(str2 != str3); //---False---

As you can see from the output of these statements, the values of each three variables are identical. However, to compare their reference equality, you need to cast each variable to object and then check their equality using the == operator, as the following shows:

Console.WriteLine((object)str1 == (object)str2); //---False---

Console.WriteLine((object)str2 == (object)str3); //---True---

However, if after the assignment the original value of the string is changed, the two strings' references will no longer be considered equal, as the following shows:

string str3 = str2;

Console.WriteLine((object)str2 == (object)str3); //---True---

str2 = "This string has changed";

Console.WriteLine((object)str2 == (object)str3); //---False---

Besides using the ==operator to test for value equality, you can also use the Equals()method, which is available as an instance method as well as a static method:

Console.WriteLine(str1 == str2); //---True---

Console.WriteLine(str1.Equals(str2)); //---True---

Console.WriteLine(string.Equals(str1,str2)); //---True---

Comparing Strings

String comparison is a common operation often performed on strings. Consider the following two string variables:

string str1 = "Microsoft";

string str2 = "microsoft";

You can use the String.Compare()static method to compare two strings:

Console.WriteLine(string.Compare(str1, str2)); // 1;str1 is greater than str2

Console.WriteLine(string.Compare(str2, str1)); // -1;str2 is less than str1

Console.WriteLine(string.Compare(str1, str2, true)); // 0;str1 equals str2

The lowercase character "m" comes before the capital "M," and hence str1is considered greater than str2. The third statement compares the two strings without considering the casing (that is, case-insensitive; it's the third argument that indicates that the comparison should ignore the casing of the strings involved).

The String.Compare()static method is overloaded, and besides the two overloaded methods (first two statements and the third statement) just shown, there are additional overloaded methods as described in the following table.

Method Description
Compare(String, String) Compares two specified Stringobjects.
Compare(String, String, Boolean) Compares two specified Stringobjects, ignoring or respecting their case.
Compare(String, String, StringComparison) Compares two specified Stringobjects. Also specifies whether the comparison uses the current or invariant culture, honors or respects case, and uses word or ordinal sort rules.
Compare(String, String, Boolean, CultureInfo) Compares two specified Stringobjects, ignoring or respecting their case, and using culture-specific information for the comparison.
Compare(String, Int32, String, Int32, Int32) Compares substrings of two specified Stringobjects.
Compare(String, Int32, String, Int32, Int32, Boolean) Compares substrings of two specified Stringobjects, ignoring or respecting their case.
Compare(String, Int32, String, Int32, Int32, StringComparison) Compares substrings of two specified Stringobjects.
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) Compares substrings of two specified Stringobjects, ignoring or respecting their case, and using culture-specific information for the comparison.

Alternatively, you can use the CompareTo()instance method, like this:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x