Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
35
Добавлен:
13.02.2015
Размер:
2.39 Mб
Скачать

How to: Generate Multiline String Literals

This example demonstrates two ways of constructing a multiline string literal.

Example

string myString1 = "This is the first line of my string.\n" +

"This is the second line of my string.\n" +

"This is the third line of the string.\n";

string myString2 = @"This is the first line of my string.

This is the second line of my string.

This is the third line of the string.";

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Создание многострочных строковых литералов

В следующем примере представлено два способа создания многострочных строковых литералов.

Пример

string myString1 = "This is the first line of my string.\n" +

"This is the second line of my string.\n" +

"This is the third line of the string.\n";

string myString2 = @"This is the first line of my string.

This is the second line of my string.

This is the third line of the string.";

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

How to: Search for a String in an Array of Strings

This example calls the IndexOf method on an array of strings to report the string number and index of the first occurrence of a substring.

Example

string[] strArray = {"ABCDEFG", "HIJKLMNOP"};

string findThisString = "JKL";

int strNumber;

int strIndex = 0;

for (strNumber = 0; strNumber < strArray.Length; strNumber++)

{

strIndex = strArray[strNumber].IndexOf(findThisString);

if (strIndex >= 0)

break;

}

System.Console.WriteLine("String number: {0}\nString index: {1}",

strNumber, strIndex);

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0.

If IndexOf does not find the substring, it returns -1.

The IndexOf method is case-sensitive and uses the current culture.

If you want more control over possible exceptions, enclose the string search in a try-catch statement.

Поиск строки в массиве строк

В этом примере вызывается метод IndexOf для массива строк, который сообщает номер строки и индекс первого вхождения подстроки.

Пример

string[] strArray = {"ABCDEFG", "HIJKLMNOP"};

string findThisString = "JKL";

int strNumber;

int strIndex = 0;

for (strNumber = 0; strNumber < strArray.Length; strNumber++)

{

strIndex = strArray[strNumber].IndexOf(findThisString);

if (strIndex >= 0)

break;

}

System.Console.WriteLine("String number: {0}\nString index: {1}",

strNumber, strIndex);

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Надежное программирование

Метод IndexOf сообщает расположение первого знака первого вхождения подстроки. Индекс начинается с нуля, поэтому номер первого знака строки равен нулю.

Если методу IndexOf не удается найти подстроку, он возвращает значение "-1".

В методе IndexOf учитывается регистр и используется текущий язык и региональные параметры.

Если необходим больший контроль над возможными исключениями, заключите строку поиска в оператор try-catch.

How to: Search Within a String

This example calls the IndexOf method on a String object to report the index of the first occurrence of a substring.

Example

string searchWithinThis = "ABCDEFGHIJKLMNOP";

string searchForThis = "DEF";

int firstCharacter = searchWithinThis.IndexOf(searchForThis);

System.Console.WriteLine("First occurrence: {0}", firstCharacter);

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0.

If IndexOf does not find the substring, it returns -1.

The IndexOf method is case-sensitive and uses the current culture.

If you want more control over possible exceptions, enclose the string search in a try-catch statement.

Поиск в строке

В этом примере вызывается метод IndexOf объекта String для отображения индекса первого вхождения подстроки.

Пример

string searchWithinThis = "ABCDEFGHIJKLMNOP";

string searchForThis = "DEF";

int firstCharacter = searchWithinThis.IndexOf(searchForThis);

System.Console.WriteLine("First occurrence: {0}", firstCharacter);

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Надежное программирование

Метод IndexOf сообщает расположение первого знака первого вхождения подстроки. Индекс начинается с нуля, поэтому номер первого знака строки равен нулю.

Если методу IndexOf не удается найти подстроку, он возвращает значение "-1".

В методе IndexOf учитывается регистр и используется текущий язык и региональные параметры.

Если необходим больший контроль над возможными исключениями, заключите строку поиска в оператор try-catch.

Arrays and Collections

Storing groups of related items of data is a basic requirement of most software applications; the two primary ways of doing this are with arrays and collections.

Arrays

Arrays are collections of objects of the same type. Because arrays can be almost any length, they can be used to store thousands or even millions of objects, but the size must be decided when the array is created. Each item in the array is accessed by an index, which is just a number that indicates the position or slot where the object is stored in the array. Arrays can be used to store both Reference Types and Value Types.

Single-Dimensional Arrays

An array is an indexed collection of objects. A single-dimensional array of objects is declared like this:

type[] arrayName;

Often, you initialize the elements in the array at the same time, like this:

int[] array = new int[5];

The default value of numeric array elements is zero, and reference elements default to null, but you can initialize values during array creation, like this:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

Or even like this:

int[] array2 = {1, 3, 5, 7, 9};

Arrays use zero-based indexes, so that the first element in the array is element 0.

string[] days = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};

System.Console.WriteLine(days[0]); // Outputs "Sun"

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]