How to: Parse Strings Using the Split Method



The following code example demonstrates how a string can be parsed using the String..::.Split method. This method works by returning an array of strings, where each element is a word. As input, Split takes an array of chars that indicate which characters are to be used as delimiters. In this example, spaces, commas, periods, colons, and tabs are used. An array containing these delimiters is passed to Split, and each word in the sentence is displayed separately using the resulting array of strings.

Example

class TestStringSplit { static void Main() {    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };      string text = "one\ttwo three:four,five six seven";    System.Console.WriteLine("Original text: '{0}'", text);      string[] words = text.Split(delimiterChars);    System.Console.WriteLine("{0} words in text:", words.Length);      foreach (string s in words)    {        System.Console.WriteLine(s);    } } }
Original text: 'one two three:four,five six seven' 7 words in text: one two three four five six seven

Анализ строк с помощью метода разделения

Следующий пример кода демонстрирует возможность анализа строки при помощи метода String..::.Split. Работа метода заключается в возврате массива строк, в котором каждый элемент представляет слово. В качестве ввода Split принимает массив символов, определяющих какие символы должны использоваться в качестве разделителей. В этом примере используются пробелы, запятые, точки, двоеточия и табуляция. Массив, содержащий эти разделители, передается в Split, и каждое слово в предложении выводится отдельно при помощи результирующего массива строк.

Пример

class TestStringSplit { static void Main() {    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };      string text = "one\ttwo three:four,five six seven";    System.Console.WriteLine("Original text: '{0}'", text);      string[] words = text.Split(delimiterChars);    System.Console.WriteLine("{0} words in text:", words.Length);      foreach (string s in words)    {        System.Console.WriteLine(s);    } } }
Original text: 'one two three:four,five six seven' 7 words in text: one two three four five six seven

 


How to: Search Strings Using String Methods

The string type, which is an alias for the System..::.String class, provides a number of useful methods for searching the contents of a string. The following example uses the IndexOf, LastIndexOf, StartsWith, and EndsWith methods.

Example

class StringSearch { static void Main() {    string str =    "Extension methods have all the capabilities of regular static methods.";    // Write the string and include the quotation marks    System.Console.WriteLine("\"{0}\"",str);      bool test1 = str.StartsWith("extension");    System.Console.WriteLine("starts with \"extension\"? {0}", test1);    bool test2 = str.StartsWith("extension",                                   System.StringComparison.OrdinalIgnoreCase);    System.Console.WriteLine("starts with \"extension\"? {0} (ignoring case)",                               test2);      bool test3 = str.EndsWith(".");    System.Console.WriteLine("ends with '.'? {0}", test3);      int first = str.IndexOf("method");    int last = str.LastIndexOf("method");    string str2 = str.Substring(first, last - first);    System.Console.WriteLine("between two \"method\" words: '{0}'", str2);      // Keep the console window open in debug mode    System.Console.WriteLine("Press any key to exit.");    System.Console.ReadKey(); } }
'A silly sentence used for silly purposes.' starts with 'a silly'? False starts with 'a silly'? True (ignore case) ends with '.'? True between two 'silly' words: 'silly sentence used for '

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

Тип 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

Анализ строк с помощью регулярных выражений[14]

Класс System.Text.RegularExpressions..::.Regex можно использовать для поиска строк. Поиск может отличаться по сложности и быть как простым, так и интенсивно использовать регулярные выражения. Ниже приведены два примера поиска строк с помощью класса Regex.

Пример

Следующий пример кода является консольным приложением, которое выполняет простой поиск строк в массиве без учета регистра. Статический метод Regex..::.IsMatch выполняет поиск заданной строки и строки, содержащей шаблон поиска. В этом случае третий аргумент указывает, что регистр знаков следует игнорировать.

ß---


The following code is a console application that uses regular expressions to validate the format of each string in an array. The validation requires that each string take the form of a telephone number in which three groups of digits are separated by dashes, the first two groups contain three digits, and the third group contains four digits. This is done by using the regular expression ^\\d{3}-\\d{3}-\\d{4}$.

class TestRegularExpressionValidation { static void Main() {    string[] numbers =    {        "123-456-7890",        "444-234-22450",        "690-203-6578",        "146-893-232",        "146-839-2322",        "4007-295-1111",        "407-295-1111",        "407-2-5555",    };    string sPattern = "^\\d{3}-\\d{3}-\\d{4}$";    foreach (string s in numbers)    {        System.Console.Write("{0,14}", s);        if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))        {            System.Console.WriteLine(" - valid");        }        else        {            System.Console.WriteLine(" - invalid");        }      } } }
123-456-7890 - valid 444-234-22450 - invalid 690-203-6578 - valid 146-893-232 - invalid 146-839-2322 - valid 4007-295-1111 - invalid 407-295-1111 - valid 407-2-5555 - invalid

Следующий пример кода является консольным приложением, которое использует регулярные выражения для проверки формата каждой строки массива. Для выполнения проверки требуется преобразование каждой строки в формат телефонного номера, в котором три группы цифр разделены дефисами, первые две группы содержат три цифры, а третья группа — четыре цифры. Для этого используется регулярное выражение ^\\d{3}-\\d{3}-\\d{4}$.

ß----


Дата добавления: 2019-03-09; просмотров: 243; Мы поможем в написании вашей работы!

Поделиться с друзьями:






Мы поможем в написании ваших работ!