Использование класса StringBuilder 


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



ЗНАЕТЕ ЛИ ВЫ?

Использование класса StringBuilder



Класс StringBuilder создает строковый буфер, который позволяет повысить производительность, если в программе обрабатывается много строк. Класс StringBuilder также позволяет заново присваивать отдельные знаки, что не поддерживается встроенным строковым типом данных. Например, данный код заменяет содержимое строки без создания новой строки:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet"); sb[0] = 'C'; System.Console.WriteLine(sb.ToString()); System.Console.ReadLine();   //Outputs Cat: the ideal pet

В этом примере объект StringBuilder используется для создания строки из набора числовых типов:

class TestStringBuilder { static void Main() { System.Text.StringBuilder sb = new System.Text.StringBuilder();   // Create a string composed of numbers 0 - 9 for (int i = 0; i < 10; i++) { sb.Append(i.ToString()); } System.Console.WriteLine(sb); // displays 0123456789   // Copy one character of the string (not possible with a System.String) sb[0] = sb[9];   System.Console.WriteLine(sb); // displays 9123456789 } }

 


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



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 142; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.219.14.63 (0.006 с.)