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, as in the following example:
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, as in the following example:
The
cat
sat
on
the
mat.
Null Strings and Empty Strings
An empty string is an instance of a System..::.String object that contains zero characters. Empty strings are used often in various programming scenarios to represent a blank text field. You can call methods on empty strings because they are valid System..::.String objects. Empty strings are initialized as follows:
string s = ""; |
By contrast, a null string does not refer to an instance of a System..::.String object and any attempt to call a method on a null string causes a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings. The following examples illustrate some cases in which a reference to a null string does and does not cause an exception to be thrown:
string str = "hello"; string nullStr = null; string emptyStr = ""; string tempStr = str + nullStr; // tempStr = "hello" bool b = (emptyStr == nullStr);// b = false; emptyStr + nullStr = ""; // creates a new empty string int len = nullStr.Length; // throws NullReferenceException |
Чтобы найти строку внутри другой строки следует использовать IndexOf(). Метод IndexOf() возвращает значение -1, если искомая строка не найдена; в противном случае возвращается индекс первого вхождения искомой строки (отсчет ведется с нуля).
string s9 = "Battle of Hastings, 1066"; System.Console.WriteLine(s9.IndexOf("Hastings")); // outputs 10 System.Console.WriteLine(s9.IndexOf("1967")); // outputs -1 |
Разделение строки на подстроки
Разделение строки на подстроки, аналогичное разделению предложения на отдельные слова, является распространенной задачей в программировании. Метод Split() получает массив разделителей типа char (например, разделителем может быть пробел) и возвращает массив подстрок. Для доступа к этому массиву можно использовать foreach, как показано в следующем примере:
|
|
ß--
Этот код выводит каждое слово в отдельной строке, как показано в следующем примере:
The
cat
sat
on
the
mat.
Строки с нулевыми значениями и пустые строки
Пустая строка — это экземпляр объекта System..::.String, содержащий 0 знаков. Пустые строки часто используются в различных сценариях программирования, представляя пустое текстовое поле. Для пустых строк можно вызывать методы, потому что такие строки являются допустимыми объектами System..::.String. Пустые строки инициализируются следующим образом:
string s = ""; |
Строки со значениями null (с нулевыми значениями), напротив, не ссылаются на экземпляр объекта System..::.String, любая попытка вызвать метод, используя в качестве объекта строку со значением null, приведет к ошибке NullReferenceException. Однако такие строки можно использовать в операциях объединения и сравнения с другими строками. В следующих примерах показаны некоторые случаи, в которых ссылка на строку со значением null вызывает либо не вызывает исключение:
|
|
ß--
Using StringBuilder
The StringBuilder class creates a string buffer that offers better performance if your program performs many string manipulations. The StringBuilder string also enables you to reassign individual characters, something the built-in string data type does not support. This code, for example, changes the content of a string without creating a new string:
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 |
In this example, a StringBuilder object is used to create a string from a set of numeric types:
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[13]
Класс 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 } } |
Дата добавления: 2019-03-09; просмотров: 240; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!