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

Working with Strings

Escape Characters

Escape characters such as "\n" (new line) and "\t" (tab) can be included in strings. The line:

string hello = "Hello\nWorld!";

is the same as:

Hello

World!

If you want to include a backward slash, it must be preceded with another backward slash. The following string:

string filePath = "\\\\My Documents\\";

is actually the same as:

\\My Documents\

Работа со строками

Escape-знаки

Строки могут содержать escape-знаки, такие как "\n" (новая строка) и "\t" (табуляция). Строка:

string hello = "Hello\nWorld!";

эквивалентна строке:

Hello

World!

Если требуется добавить в строку обратную косую черту, перед ней нужно поставить еще одну обратную косую черту. Следующая строка

string filePath = "\\\\My Documents\\";

эквивалентна строке

\\My Documents\

The @ Symbol

The @ symbol specifies that escape characters and line breaks should be ignored when the string is created. The following two strings are therefore identical:

string p1 = "\\\\My Documents\\My Files\\";

string p2 = @"\\My Documents\My Files\";

ToString()

The C# built-in data types all provide the ToString method, which converts a value to a string. This method can be used to convert numeric values into strings, like this:

int year = 1999;

string msg = "Eve was born in " + year.ToString();

System.Console.WriteLine(msg); // outputs "Eve was born in 1999"

Символ @

Символ @ указывает, что при создании строки следует игнорировать escape-знаки и переносы строки. Следующие две строки являются идентичными.

string p1 = "\\\\My Documents\\My Files\\";

string p2 = @"\\My Documents\My Files\";

ToString()

У всех встроенных типов данных C# есть метод ToString, преобразующий значение в строку. Этот метод может быть использован для преобразования числовых значений в строки следующим образом.

int year = 1999;

string msg = "Eve was born in " + year.ToString();

System.Console.WriteLine(msg); // outputs "Eve was born in 1999"

Accessing Individual Characters

Individual characters contained in a string can be accessed using methods such as Substring, Replace, Split and Trim.

string s3 = "Visual C# Express";

System.Console.WriteLine(s3.Substring(7, 2)); // outputs "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic")); // outputs "Visual Basic Express"

It is also possible to copy the characters into a character array, like this:

string s4 = "Hello, World";

char[] arr = s4.ToCharArray(0, s4.Length);

foreach (char c in arr)

{

System.Console.Write(c); // outputs "Hello, World"

}

Individual characters from a string can be accessed with an index, like this:

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)

{

System.Console.Write(s5[s5.Length - i - 1]);

// outputs "sdrawkcab gnitnirP"

}

Доступ к отдельным знакам

К отдельным знакам, содержащимся в строке, можно получить доступ с помощью таких методов как Substring, Replace, Split и Trim.

string s3 = "Visual C# Express";

System.Console.WriteLine(s3.Substring(7, 2));

// Output: "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic"));

// Output: "Visual Basic Express"

Также можно скопировать знаки в массив знаков, как показано в следующем примере.

string s4 = "Hello, World";

char[] arr = s4.ToCharArray(0, s4.Length);

foreach (char c in arr)

{

System.Console.Write(c); // outputs "Hello, World"

}

Доступ к отдельным знакам в строке возможен с помощью индекса, как показано в следующем примере.

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)

{

System.Console.Write(s5[s5.Length - i - 1]);

}

// Output: "sdrawkcab gnitnirP"