logo search
CSharp_Prog_Guide

Сравнения

Самый простой способ сравнения двух строк — использовать операторы == и !=, осуществляющие сравнение с учетом регистра.

string color1 = "red";

string color2 = "green";

string color3 = "red";

if (color1 == color3)

{

System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

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

}

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

--

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

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

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

The

cat

sat

on

the

mat.

Null Strings and Empty Strings

An empty string is an instance of a System..::.String object that contains zero characters. Empty strings are used often in various programming scenarios to represent a blank text field. You can call methods on empty strings because they are valid System..::.String objects. Empty strings are initialized as follows:

string s = "";

By contrast, a null string does not refer to an instance of a System..::.String object and any attempt to call a method on a null string causes a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings. The following examples illustrate some cases in which a reference to a null string does and does not cause an exception to be thrown:

string str = "hello";

string nullStr = null;

string emptyStr = "";

string tempStr = str + nullStr; // tempStr = "hello"

bool b = (emptyStr == nullStr);// b = false;

emptyStr + nullStr = ""; // creates a new empty string

int len = nullStr.Length; // throws NullReferenceException

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