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

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

Интервал:

Закладка:

Сделать

int num3 = int.Parse(str2,

System.Globalization.NumberStyles.AllowThousands);

Console.WriteLine(num3); //---9876---

Here is another example:

string str3 = "1,239,876";

num3 = int.Parse(str3,

System.Globalization.NumberStyles.AllowThousands);

Console.WriteLine(num3); //---1239876---

What about the reverse — formatting a number with the comma separator? Here is the solution:

num3 = 9876;

Console.WriteLine("{0:#,0}", num3); //---9,876---

num3 = 1239876;

Console.WriteLine("{0:#,0}", num3); //---1,239,876---

Last, to format a special number (such as a phone number), use the following format specifier:

long phoneNumber = 1234567890;

Console.WriteLine("{0:###-###-####}", phoneNumber); //---123-456-7890---

The StringBuilder Class

Earlier in this chapter you saw how to easily concatenate two strings by using the +operator. That's fine if you are concatenating a small number of strings, but it is not recommended for large numbers of strings. The reason is that Stringobjects in .NET are immutable , which means that once a string variable is initialized, its value cannot be changed. When you concatenate another string to an existing one, you actually discard its old value and create a new string object containing the result of the concatenation. When you repeat this process several times, you incur a performance penalty as new temporary objects are created and old objects discarded.

One important application of the StringBuilderclass is its use in .NET interop with native C/C++ APIs that take string arguments and modify strings. One example of this is the Windows API function GetWindowText(). This function has a second argument that takes a TCHAR*parameter. To use this function from .NET code, you would need to pass a StringBuilderobject as this argument.

Consider the following example, where you concatenate all the numbers from 0 to 9999:

int counter = 9999;

string s = string.Empty;

for (int i = 0; i <= counter; i++) {

s += i.ToString();

}

Console.WriteLine(s);

At first glance, the code looks innocent enough. But let's use the Stopwatchobject to time the operation. Modify the code as shown here:

int counter = 9999;

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

sw.Start();

string s = string.Empty;

for (int i = 0; i <= counter; i++) {

s += i.ToString();

}

sw.Stop();

Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);

Console.WriteLine(s);

On average, it took about 374 ms on my computer to run this operation. Let's now use the StringBuilderclass in .NET to perform the string concatenation, using its Append()method:

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

sw.Start();

StringBuilder sb = new StringBuilder();

for (int i = 0; i <= 9999; i++) {

sb.Append(i.ToString());

}

sw.Stop();

Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);

Console.WriteLine(sb.ToString());

On average, it took about 6 ms on my computer to perform this operation. As you can deduce, the improvement is drastic — 98% ((374-6)/374). If you increase the value of the loop variant (counter), you will find that the improvement is even more dramatic.

The StringBuilderclass represents a mutable string of characters. Its behavior is like the Stringobject except that its value can be modified once it has been created.

The StringBuilderclass contains some other important methods, which are described in the following table.

Method Description
Append Appends the string representation of a specified object to the end of this instance.
AppendFormat Appends a formatted string, which contains zero or more format specifiers, to this instance. Each format specification is replaced by the string representation of a corresponding object argument.
AppendLine Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance.
CopyTo Copies the characters from a specified segment of this instance to a specified segment of a destination Chararray.
Insert Inserts the string representation of a specified object into this instance at a specified character position.
Remove Removes the specified range of characters from this instance.
Replace Replaces all occurrences of a specified character or string in this instance with another specified character or string.
ToString Converts the value of a StringBuilderto a String.

Regular Expressions

When dealing with strings, you often need to perform checks on them to see if they match certain patterns. For example, if your application requires the user to enter an email address so that you can send them a confirmation email later on, it is important to at least verify that the user has entered a correctly formatted email address. To perform the checking, you can use the techniques that you have learnt earlier in this chapter by manually looking for specific patterns in the email address. However, this is a tedious and mundane task.

A better approach would be to use regular expressions — a language for describing and manipulating text. Using regular expressions, you can define the patterns of a text and match it against a string. In the .NET Framework, the System.Text.RegularExpressionsnamespace contains the RegExclass for manipulating regular expressions.

Searching for a Match

To use the RegExclass, first you need to import the System.Text.RegularExpressionsnamespace:

using System.Text.RegularExpressions;

The following statements shows how you can create an instance of the RegEx class, specify the pattern to search for, and match it against a string:

string s = "This is a string";

Regex r = new Regex("string");

if (r.IsMatch(s)) {

Console.WriteLine("Matches.");

}

In this example, the Regexclass takes in a string constructor, which is the pattern you are searching for. In this case, you are searching for the word "string" and it is matched against the s string variable. The IsMatch()method returns Trueif there is a match (that is, the string s contains the word "string").

To find the exact position of the text "string" in the variable, you can use the Match()method of the RegExclass. It returns a Matchobject that you can use to get the position of the text that matches the search pattern using the Index property:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x