logo search
CSharp_Prog_Guide

Навигация по содержимому строки с помощью строковых методов

Тип string, являющийся псевдонимом класса System..::.String, позволяет использовать несколько полезных методов для навигации по содержимому строки. В следующем примере используются методы IndexOf, LastIndexOf, StartsWith и EndsWith.

Пример

---

How to: Search Strings Using Regular Expressions

The System.Text.RegularExpressions..::.Regex class can be used to search strings. These searches can range in complexity from very simple to making full use of regular expressions. The following are two examples of string searching by using the Regex class.

Example

The following code is a console application that performs a simple case-insensitive search of the strings in an array. The static method Regex..::.IsMatch performs the search given the string to search and a string that contains the search pattern. In this case, a third argument is used to indicate that case should be ignored. For more information, see System.Text.RegularExpressions..::.RegexOptions.

class TestRegularExpressions

{

static void Main()

{

string[] sentences =

{

"cow over the moon",

"Betsy the Cow",

"cowering in the corner",

"no match here"

};

string sPattern = "cow";

foreach (string s in sentences)

{

System.Console.Write("{0,24}", s);

if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern,

System.Text.RegularExpressions.RegexOptions.IgnoreCase))

{

System.Console.WriteLine(" (match for '{0}' found)", sPattern);

}

else

{

System.Console.WriteLine();

}

}

}

}

cow over the moon (match for 'cow' found)

Betsy the Cow (match for 'cow' found)

cowering in the corner (match for 'cow' found)

no match here