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

Объединение нескольких строк

Имеется несколько способов объединения нескольких строк: перегрузка оператора + для класса String и использование класса StringBuilder. Оператор + удобен в использовании и позволяет сформировать наглядный код, но он работает последовательно. При каждом использовании оператора создается новая строка, поэтому создание цепочки из нескольких операторов неэффективно. Пример.

string two = "two";

string str = "one " + two + " three";

System.Console.WriteLine(str);

Хотя в коде фигурируют четыре строки (три объединяемых строки и одна строка результата, содержащая все три), всего создается пять строк, поскольку сначала объединяются первые две строки, создавая одну результирующую строку. Третья строка присоединяется отдельно, формируя окончательную строку, хранящуюся в str.

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

Пример

В следующем коде используется метод "Append" класса StringBuilder для объединения трех строк без "эффекта цепочки" оператора +.

---

How to: Modify String Contents

Strings are immutable, so it is not possible to modify the contents of string. The contents of a string can, however, be extracted into a non-immutable form, modified, and then formed into a new string instance.

Example

The following example uses the ToCharArray method to extract the contents of a string into an array of the char type. Some of the elements of this array are then modified. The char array is then used to create a new string instance.

class ModifyStrings

{

static void Main()

{

string str = "The quick brown fox jumped over the fence";

System.Console.WriteLine(str);

char[] chars = str.ToCharArray();

int animalIndex = str.IndexOf("fox");

if (animalIndex != -1)

{

chars[animalIndex++] = 'c';

chars[animalIndex++] = 'a';

chars[animalIndex] = 't';

}

string str2 = new string(chars);

System.Console.WriteLine(str2);

}

}

The quick brown fox jumped over the fence

The quick brown cat jumped over the fence

Изменение содержимого строки

Строки являются неизменяемыми, поэтому их содержимое изменить невозможно. Однако содержимое строки можно извлечь в форму для редактирования, выполнить изменения, а затем передать в новый экземпляр строки.

Пример

В следующем примере для извлечения содержимого строки в массив типа char используется метод ToCharArray. Затем некоторые элементы массива изменяются. После этого массив char используется для создания нового экземпляра строки.

---

How to: Determine Whether a String Contains a Numeric Value

To determine whether a string is a valid representation of a specified numeric type, use the static TryParse method. This method is implemented by all primitive numeric types and also by types such as DateTime and IPAddress. The following example shows how to determine whether "108" is a valid int.

int i = 0;

string s = "108";

bool result = int.TryParse(s, out i); //i now = 108

If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

Note:

A string may contain only numeric characters and still not be valid for the type whose TryParse method that you use. For example, "256" is not a valid value for byte but it is valid for int. "98.6" is not a valid value for int but it is a valid decimal.