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

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

Чтобы изменить регистр букв в строке (сделать их заглавными или строчными) следует использовать 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

Splitting a String into Substrings

Splitting a string into substrings, such as, splitting a sentence into individual words, is a common programming task. The Split() method takes a char array of delimiters, for example, a space character, and returns an array of substrings. You can access this array with foreach, like this:

char[] delimit = new char[] {' '};

string s10 = "The cat sat on the mat.";

foreach (string substr in s10.Split(delimit))

{

System.Console.WriteLine(substr);

}

This code outputs each word on a separate line, like this:

The

cat

sat

on

the

mat.

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