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

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

Интервал:

Закладка:

Сделать

Console.WriteLine(str1.CompareTo(str2)); // 1; str1 is greater than str2

Console.WriteLine(str2.CompareTo(str1)); // -1; str2 is less than str1

Note that comparisons made by the CompareTo()instance method are always case sensitive.

Creating and Concatenating Strings

The Stringclass in the .NET Framework provides a number of methods that enable you to create or concatenate strings.

The most direct way of concatenating two strings is to use the " +" operator, like this:

string str1 = "Hello ";

string str2 = "world!";

string str3 = str1 + str2;

Console.WriteLine(str3); //---Hello world!---

The String.Format()static method takes the input of multiple objects and creates a new string. Consider the following example:

string Name = "Wei-Meng Lee";

int age = 18;

string str1 = string.Format("My name is {0} and I am {1} years old", Name, age);

//---str1 is now "My name is Wei-Meng Lee and I am 18 years old"---

Console.WriteLine(str1);

Notice that you supplied two variables of string and int type and the Format()method automatically combines them to return a new string.

The preceding example can be rewritten using the String.Concat()static method, like this:

string str1 =

string.Concat("My name is ", Name, " and I am ", age, " years old");

//---str1 is now "My name is Wei-Meng Lee and I am 18 years old"---

Console.WriteLine(str1);

Strings Are Immutable

In .NET, all string objects are immutable. This means that once a string variable is initialized, its value cannot be changed. And when you modify the value of a string, a new copy of the string is created and the old copy is discarded. Hence, all methods that process strings return a copy of the modified string — the original string remains intact.

For example, the Insert()instance method inserts a string into the current string and returns the modified string:

str1 = str1.Insert(10, "modified ");

In this statement, you have to assign the returned result to the original string to ensure that the new string is modified.

The String.Join()static method is useful when you need to join a series of strings stored in a string array. The following example shows the strings in a string array joined using the Join()method:

string[] pts = { "1,2", "3,4", "5,6" };

string str1 = string.Join("|", pts);

Console.WriteLine(str1); //---1,2|3,4|5,6---

To insert a string into an existing string, use the instance method Insert(), as demonstrated in the following example:

string str1 = "This is a string";

str1 = str1.Insert(10, "modified ");

Console.WriteLine(str1); //---This is a modified string---

The Copy()instance method enables you to copy part of a string into a char array. Consider the following example:

string str1 = "This is a string";

char[] ch = { '*', '*', '*', '*', '*', '*', '*', '*' };

str1.CopyTo(0, ch, 2, 4); Console.WriteLine(ch); //---**This**---

The first parameter of the CopyTo()method specifies the index of the string to start copying from. The second parameter specifies the char array. The third parameter specifies the index of the array to copy into, while the last parameter specifies the number of characters to copy.

If you need to pad a string with characters to achieve a certain length, use the PadLeft()and PadRight()instance methods, as the following statements show:

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

str2 = str1.PadLeft(20, '*');

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

str2 = str1.PadRight(20, '*');

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

Trimming Strings

To trim whitespace from the beginning of a string, the end of a string, or both, you can use the TrimStart(), TrimEnd(), or Trim()instance methods, respectively. The following statements demonstrate the use of these methods:

string str1 = " Computer ";

string str2;

Console.WriteLine(str1); //---" Computer "---

str2 = str1.Trim();

Console.WriteLine(str2); //---"Computer"---

str2 = str1.TrimStart();

Console.WriteLine(str2); //---"Computer "---

str2 = str1.TrimEnd();

Console.WriteLine(str2); //---" Computer"---

Splitting Strings

One common operation with string manipulation is splitting a string into smaller strings. Consider the following example where a string contains a serialized series of points:

string str1 = "1,2|3,4|5,6|7,8|9,10";

Each point ("1, 2", "3, 4", and so on) is separated with the | character. You can use the Split()instance method to split the given string into an array of strings:

string[] strArray = str1.Split('|');

Once the string is split, the result is stored in the string array strArrayand you can print out each of the smaller strings using a foreachstatement:

foreach (string s in strArray) Console.WriteLine(s);

The output of the example statement would be:

1,2

3,4

5,6

7,8

9,10

You can further split the points into individual coordinates and then create a new Pointobject, like this:

string str1 = "1,2|3,4|5,6|7,8|9,10";

string[] strArray = str1.Split('|');

foreach (string s in strArray) {

string[] xy= s.Split(',');

Point p = new Point(Convert.ToInt16(xy[0]), Convert.ToInt16(xy[1]));

Console.WriteLine(p.ToString());

}

The output of the above statements would be:

{X=1,Y=2}

{X=3,Y=4}

{X=5,Y=6}

{X=7,Y=8}

{X=9,Y=10}

Searching and Replacing Strings

Occasionally, you need to search for a specific occurrence of a string within a string. For this purpose, you have several methods that you can use.

To look for the occurrence of a word and get its position, use the IndexOf()and LastIndexOf()instance methods. IndexOf()returns the position of the first occurrence of a specific word from a string, while LastIndexOf()returns the last occurrence of the word. Here's an example:

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

Console.WriteLine(str1.IndexOf("long")); //---10---

Console.WriteLine(str1.LastIndexOf("long")); //---20---

To find all the occurrences of a word, you can write a simple loop using the IndexOf()method, like this:

int position = -1;

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

do {

position = str1.IndexOf("long", ++position);

if (position > 0) Console.WriteLine(position);

} while (position > 0);

This prints out the following:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x