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

Changing Case

To change the letters in a string to upper or lower case, use ToUpper() or ToLower(), like this:

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"

Смена регистра

Чтобы изменить регистр букв в строке (сделать их заглавными или строчными) следует использовать ToUpper() или ToLower(), как показано в следующем примере.

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 != symbols, 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 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 based on whether one string is less-than (<) or greater-than (>) another. When comparing strings, the Unicode value is used, and lower case has a smaller value than upper case.

// Enter different values for string1 and string2 to

// experiment 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

Для строковых объектов также существует метод CompareTo(), возвращающий целочисленное значение, которое зависит от того, что одна строка может быть меньше (<) или больше (>) другой. При сравнении строк используется значение Юникода, при этом значение строчных букв меньше, чем значение заглавных.

// Enter different values for string1 and string2 to

// experiment with behavior of CompareTo

string string1 = "ABC";

string string2 = "abc";

int result2 = string1.CompareTo(string2);

if (result2 > 0)

{

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

}

else if (result2 == 0)

{

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

}

else if (result2 < 0)

{

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

}

// Output: ABC is less than abc46

To search for a string inside another string, use IndexOf(). IndexOf() returns -1 if the search string is not found; otherwise, it returns the zero-based index of the first location at which it occurs.

string s9 = "Battle of Hastings, 1066";

System.Console.WriteLine(s9.IndexOf("Hastings")); // outputs 10

System.Console.WriteLine(s9.IndexOf("1967")); // outputs -1

Чтобы найти строку внутри другой строки следует использовать IndexOf(). IndexOf() возвращает значение -1, если искомая строка не найдена; в противном случае возвращается индекс первого вхождения искомой строки (отсчет ведется с нуля).

string s9 = "Battle of Hastings, 1066";

System.Console.WriteLine(s9.IndexOf("Hastings")); // outputs 10

System.Console.WriteLine(s9.IndexOf("1967")); // outputs -1