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

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

Следующий пример кода демонстрирует возможность анализа строки при помощи метода 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 '