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

Работа со строками 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"

}

Точные строки: символ @

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

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

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

Чтобы поставить в точной строке знак двойных кавычек, нужно использовать по два таких знака, как показано в следующем примере:

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

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

К отдельным знакам, содержащимся в строке, можно получить доступ с помощью таких методов как SubString() и 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"

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

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]); // outputs "sdrawkcab gnitnirP"

}

Changing Case

To change the letters in a string to uppercase or lowercase, use ToUpper() or ToLower(), as in the following example:

string s6 = "Battle of Hastings, 1066";

System.Console.WriteLine(s6.ToUpper()); // outputs "BATTLE OF HASTINGS 1066"

System.Console.WriteLine(s6.ToLower()); // outputs "battle of hastings 1066"

Comparisons

The simplest way to compare two strings is to use the == and != operators, which perform a case-sensitive comparison.

string color1 = "red";

string color2 = "green";

string color3 = "red";

if (color1 == color3)

{

System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

System.Console.WriteLine("Not equal");

}

String objects also have a CompareTo() method that returns an integer value that is based on whether one string is less-than (<), equal to (==) or greater-than (>) another. When comparing strings, the Unicode value is used, and lowercase has a smaller value than uppercase. For more information about the rules for comparing strings, see CompareTo()()().

// Enter different values for string1 and string2 to

// experiement with behavior of CompareTo

string string1 = "ABC";

string string2 = "abc";

int result = string1.CompareTo(string2);

if (result > 0)

{

System.Console.WriteLine("{0} is greater than {1}", string1, string2);

}

else if (result == 0)

{

System.Console.WriteLine("{0} is equal to {1}", string1, string2);

}

else if (result < 0)

{

System.Console.WriteLine("{0} is less than {1}", string1, string2);

}

// Outputs: ABC is less than abc