logo
CSharp_Prog_Guide

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

Класс 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