Использование класса 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

}

}


How to: Generate Multiline String Literals

This example demonstrates two ways of constructing a multiline string literal.

Example

string myString1 = "This is the first line of my string.\n" + "This is the second line of my string.\n" + "This is the third line of the string.\n"; string myString2 = @"This is the first line of my string. This is the second line of my string. This is the third line of the string.";

Compiling the Code

Copy the code and paste it into the Main method of a console application.


Создание многострочных строковых литералов

В следующем примере представлено два способа создания многострочных строковых литералов.

Пример

string myString1 = "This is the first line of my string.\n" + "This is the second line of my string.\n" + "This is the third line of the string.\n"; string myString2 = @"This is the first line of my string. This is the second line of my string. This is the third line of the string.";

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.


How to: Search for a String in an Array of Strings

This example calls the IndexOf method on an array of strings to report the string number and index of the first occurrence of a substring.

 

Example

string[] strArray = {"ABCDEFG", "HIJKLMNOP"}; string findThisString = "JKL"; int strNumber; int strIndex = 0; for (strNumber = 0; strNumber < strArray.Length; strNumber++) { strIndex = strArray[strNumber].IndexOf(findThisString); if (strIndex >= 0) break; } System.Console.WriteLine("String number: {0}\nString index: {1}", strNumber, strIndex);

Compiling the Code

 

Copy the code and paste it into the Main method of a console application.

 

Robust Programming

 

The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0.

If IndexOf does not find the substring, it returns -1.

The IndexOf method is case-sensitive and uses the current culture.

If you want more control over possible exceptions, enclose the string search in a try-catch statement.




Дата добавления: 2022-05-27; просмотров: 133;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.007 сек.