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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

□ Explore the System.Stringclass

□ Learn how to represent special characters in string variables

□ Manipulate strings with various methods

□ Format strings

□ Use the StringBuilderclass to create and manipulate strings

□ Use Regular Expressions to match string patterns

The System.String Class

The .NET Framework contains the System.Stringclass for string manipulation. To create an instance of the Stringclass and assign it a string, you can use the following statements:

String str1;

str1 = "This is a string";

C# also provides an alias to the Stringclass: string(lowercase "s"). The preceding statements can be rewritten as:

string str1; //---equivalent to String str1;---

str1 = "This is a string";

You can declare a string and assign it a value in one statement, like this:

string str2 = "This is another string";

In .NET, a string is a reference type but behaves very much like a value type. Consider the following example of a typical reference type:

Button btn1 = new Button() { Text = "Button 1" };

Button btn2 = btn1;

btn1.Text += " and 2"; //---btn1.text is now "Button 1 and 2"---

Console.WriteLine(btn1.Text); //---Button 1 and 2---

Console.WriteLine(btn2.Text); //---Button 1 and 2---

Here, you create an instance of a Buttonobject ( btn1) and then assign it to another variable ( btn2). Both btn1and btn2are now pointing to the same object, and hence when you modify the Textproperty of btn1, the changes can be seen in btn2(as is evident in the output of the WriteLine()statements).

Because strings are reference types, you would expect to see the same behavior as exhibited in the preceding block of code. For example:

string str1 = "String 1";

string str2 = str1;

str1and str2should now be pointing to the same instance. Make some changes to str1by appending some text to it:

str1 += " and some other stuff";

And then print out the value of these two strings:

Console.WriteLine(str1); //---String 1 and some other stuff---

Console.WriteLine(str2); //---String 1---

Are you surprised to see that the values of the two strings are different? What actually happens when you do the string assignment ( string str2 = str1) is that str1is copied to str2( str2holds a copy of str1; it does not points to it). Hence, changes made to str1are not reflected in str2.

A string cannot be a value type because of its unfixed size. All values types (int, double, and so on) have fixed size.

A string is essentially a collection of Unicode characters. The following statements show how you enumerate a string as a collection of char and print out the individual characters to the console:

string str1 = "This is a string";

foreach (char c in str1) {

Console.WriteLine(c);

}

Here's this code's output:

T

h

i

s

i

s

a

s

t

r

i

n

g

Escape Characters

Certain characters have special meaning in strings. For example, strings are always enclosed in double quotation marks, and if you want to use the actual double-quote character in the string, you need to tell the C# compiler by "escaping" the character's special meaning. For instance, say you need to represent the following in a string:

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

Because the sentence contains the double-quote characters, simply using a pair of double- quotes to contain it will cause an error:

//---error--- string quotation;

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

To represent the double-quote character in a string, you use the backslash (\) character to turn off its special meanings, like this:

string quotation =

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

Console.WriteLine(quotation);

The output is shown in Figure 8-1.

Figure 81 A backslash then is another special character To represent the - фото 131

Figure 8-1

A backslash, then, is another special character. To represent the C:\Windows path, for example, you need to turn off the special meaning of \ by using another \ , like this:

string path = "C:\\Windows";

What if you really need two backslash characters in your string, as in the following?

"\\servername\path"

In that case, you use the backslash character twice, once for each of the backslash characters you want to turn off, like this:

string UNC = "\\\\servername\\path";

In addition to using the \character to turn off the special meaning of characters like the double-quote (") and backslash (\), there are other escape characters that you can use in strings.

One common escape character is the \n. Here's an example:

string lines = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5";

Console.WriteLine(lines);

The \nescape character creates a newline, as Figure 8-2 shows.

Figure 82 You can also use tto insert tabs into your string as the following - фото 132

Figure 8-2

You can also use \tto insert tabs into your string, as the following example shows (see also Figure 8-3):

string columns1 = "Column 1\tColumn 2\tColumn 3\tColumn 4";

string columns2 = "1\t5\t25\t125";

Console.WriteLine(columns1);

Console.WriteLine(columns2);

Figure 83 You learn more about formatting options in the section String - фото 133

Figure 8-3

You learn more about formatting options in the section "String Formatting" later in this chapter.

Besides the \nand \tescape characters, C# also supports the \rescape character. \ris the carriage return character. Consider the following example:

string str1 = " One";

string str2 = "Two";

Console.Write(str1);

Console.Write(str2);

The output is shown in Figure 8-4.

Figure 84 However if you prefix a rescape character to the beginning of - фото 134

Figure 8-4

However, if you prefix a \rescape character to the beginning of str2, the effect will be different:

string str1 = " One";

string str2 = "\rTwo";

Console.Write(str1);

Console.Write(str2);

The output is shown in Figure 8-5.

Figure 85 The rescape character simply brings the cursor to the beginning of - фото 135

Figure 8-5

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

Интервал:

Закладка:

Сделать

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

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


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

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

x