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

Splitting a String into Substrings

Splitting a string into substrings, such as, splitting a sentence into individual words, is a common programming task. The Split() method takes a char array of delimiters, for example, a space character, and returns an array of substrings. You can access this array with foreach, like this:

char[] delimit = new char[] {' '};

string s10 = "The cat sat on the mat.";

foreach (string substr in s10.Split(delimit))

{

System.Console.WriteLine(substr);

}

This code outputs each word on a separate line, like this:

The

cat

sat

on

the

mat.

Разделение строки на подстроки

Разделение строки на подстроки, аналогичное разделению предложения на отдельные слова, является распространенной задачей в программировании. Метод Split() получает массив разделителей типа char (например, разделителем может быть пробел) и возвращает массив подстрок. Доступ к массиву можно получить только с помощью foreach, как показано в следующем примере.43

char[] delimit = new char[] {' '};

string s10 = "The cat sat on the mat.";

foreach (string substr in s10.Split(delimit))

{

System.Console.WriteLine(substr);

}

Этот код выводит каждое слово в отдельной строке, как показано в следующем примере.

The

cat

sat

on

the

mat.

Using StringBuilder

The StringBuilder class creates a string buffer that offers better performance if your program performs a lot of string manipulation. The StringBuilder class also allows you to reassign individual characters, something the built-in string data type does not support.

In this example, a StringBuilder object is created, and its contents are added one by one using the Append method.

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

}

}

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

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

В следующем примере создается объект StringBuilder и его содержимое последовательно добавляется с помощью метода Append.

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

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]