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

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

Интервал:

Закладка:

Сделать

10

15

20

To search for the occurrence of particular character, use the IndexOfAny()instance method. The following statements search the str1string for the any of the characters a, b, c, d, or e, specified in the chararray:

char[] anyof = "abcde".ToCharArray();

Console.WriteLine(str1.IndexOfAny(anyof)); //---8---

To obtain a substring from within a string, use the Substring()instance method, as the following example shows:

string str1 = "This is a long string...";

string str2;

Console.WriteLine(str1.Substring(10)); //---long string...---

Console.WriteLine(str1.Substring(10, 4)); //---long---

To find out if a string begins with a specific string, use the StartsWith()instance method. Likewise, to find out if a string ends with a specific string, use the EndsWith()instance method. The following statements illustrate this:

Console.WriteLine(str1.StartsWith("This")); //---True---

Console.WriteLine(str1.EndsWith("...")); //---True---

To remove a substring from a string beginning from a particular index, use the Remove() instance method:

str2 = str1.Remove(10);

Console.WriteLine(str2); //---"This is a"---

This statement removes the string starting from index position 10. To remove a particular number of characters, you need to specify the number of characters to remove in the second parameter:

str2 = str1.Remove(10,5); //---remove 5 characters from index 10---

Console.WriteLine(str2); //---"This is a string..."---

To replace a substring with another, use the Replace()instance method:

str2 = str1.Replace("long", "short");

Console.WriteLine(str2); //---"This is a short string..."---

To remove a substring from a string without specifying its exact length, use the Replace()method, like this:

str2 = str1.Replace("long ", string.Empty);

Console.WriteLine(str2); //---"This is a string..."---

Changing Case

To change the casing of a string, use the ToUpper()or ToLower()instance methods. The following statements demonstrate their use:

string str1 = "This is a string"; string str2;

str2 = str1.ToUpper();

Console.WriteLine(str2); //---"THIS IS A STRING"---

str2 = str1.ToLower();

Console.WriteLine(str2); //---"this is a string"---

String Formatting

You've seen the use of the Console.WriteLine()method to print the output to the console. For example, the following statement prints the value of num1to the console:

int num1 = 5;

Console.WriteLine(num1); //---5---

You can also print the values of multiple variables like this:

int num1 = 5;

int num2 = 12345;

Console.WriteLine(num1 + " and " + num2); //---5 and 12345---

If you have too many variables to print (say more than five), though, the code can get messy very quickly. A better way would be to use a format specifier, like this:

Console.WriteLine("{0} and {1}", num1, num2); //---5 and 12345---

A format specifier ( {0}, {1}, and so forth) automatically converts all data types to string. Format specifiers are labeled sequentially ( {0}, {1}, {2}, and so on). Each format specifier is then replaced with the value of the variable to be printed. The compiler looks at the number in the format specifier, takes the argument with the same index in the argument list, and makes the substitution. In the preceding example, num1 and num2 are the arguments for the format specifiers.

What happens if you want to print out the value of a number enclosed with the {}characters? For example, say that you want to print the string {5}when the value of num1 is 5. You can do something like this:

num1 = 5;

Console.WriteLine("{{{0}}}", num1); //---{5}---

Why are there two additional sets of {}characters for the format specifier? Well, if you only have one additional set of {}characters, the compiler interprets this to mean that you want to print the string literal {0}, as the following shows:

num1 = 5;

Console.WriteLine("{{0}}", num1); //---{0}---

The two additional sets of {}characters indicate to the compiler that you want to specify a format specifier and at the same time surround the value with a pair of {}characters.

And as demonstrated earlier, the Stringclass contains the Format()static method, which enables you to create a new string (as well as perform formatting on string data). The preceding statement could be rewritten using the following statements:

string formattedString = string.Format("{{{0}}}", num1);

Console.WriteLine(formattedString); //---{5}---

To format numbers, you can use the format specifiers as shown here:

num1=5;

Console.WriteLine("{0:N}", num1); //---5.00---

Console.WriteLine("{0:00000}", num1);- //---00005---

//---OR---

Console.WriteLine("{0:d5}", num1); //---00005---

Console.WriteLine("{0:d4}", num1); //---0005---

Console.WriteLine("{0,5:G}", num1);--- //--- 5 (4 spaces on left)---

For a detailed list of format specifiers you can use for formatting strings, please refer to the MSDN documentation under the topics "Standard Numeric Format Strings" and "Custom Numeric Format Strings. "

You can also print out specific strings based on the value of a number. Consider the following example:

num1 = 0;

Console.WriteLine("{0:yes;;no}", num1); //---no--

num1 = 1;

Console.WriteLine("{0:yes;;no}", num1); //---yes---

num1 = 5;

Console.WriteLine("{0:yes;;no}", num1); //---yes---

In this case, the format specifier contains two strings: yes and no. If the value of the variable ( num) is nonzero, the first string will be returned ( yes). If the value is 0, then it returns the second string ( no). Here is another example:

num1 = 0;

Console.WriteLine("{0:OK;;Cancel}", num1); //---Cancel---

num1 = 1;

Console.WriteLine("{0:OK;;Cancel}", num1); //---OK---

num1 = 5;

Console.WriteLine("{0:OK;;Cancel}", num1); //---OK---

For decimal number formatting, use the following format specifiers:

double val1 = 3.5;

Console.WriteLine("{0:##.00}", val1);-- //---3.50---

Console.WriteLine("{0:##.000}", val1);- //---3.500---

Console.WriteLine("{0:0##.000}", val1); //---003.500---

There are times when numbers are represented in strings. For example, the value 9876 may be represented in a string with a comma denoting the thousandth position. In this case, you cannot simply use the Parse()method from the int class, like this:

string str2 = "9,876";

int num3 = int.Parse(str2); //---error---

To correctly parse the string, use the following statement:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x