logo
CSharp_Prog_Guide

Работа со строками Escape-знаки

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

string hello = "Hello\nWorld!";

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

Hello

World!

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

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

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

\\My Documents\

Verbatim Strings: The @ Symbol

The @ symbol tells the string constructor to ignore escape characters and line breaks. The following two strings are therefore identical:

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

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

In a verbatim string, you escape the double quotation mark character with a second double quotation mark character, as in the following example:

string s = @"You say ""goodbye"" and I say ""hello""";

Accessing Individual Characters

Individual characters that are contained in a string can be accessed by using methods such as SubString() and Replace().

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, as in the following example:

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, as in the following example:

string s5 = "Printing backwards";

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

{

System.Console.Write(s5[s5.Length - i - 1]); // outputs "sdrawkcab gnitnirP"

}