- Split Container. Splitter Distance Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Разделение строк с помощью метода String.Split на C# How to separate strings using String.Split in C#
- Извлечение подстрок из строки Extract substrings from a string
- Метод String.Split String.Split method
- Регулярные выражения Regular expressions
- Методы String.IndexOf и String.Substring String.IndexOf and String.Substring methods
Split Container. Splitter Distance Свойство
Определение
Возвращает или задает местоположение разделителя (в пикселях) от левого или верхнего края объекта SplitContainer. Gets or sets the location of the splitter, in pixels, from the left or top edge of the SplitContainer.
Значение свойства
Значение Int32, представляющее местоположение разделителя (в пикселях) относительно левого или верхнего края объекта SplitContainer. An Int32 representing the location of the splitter, in pixels, from the left or top edge of the SplitContainer. Значение по умолчанию равно 50 пикселям. The default value is 50 pixels.
Исключения
Значение меньше нуля. The value is less than zero.
Значение несовместимо с ориентацией. The value is incompatible with the orientation.
Примеры
В следующем примере кода указывается, что начальное расстояние вертикального разделителя от левого края контейнера составляет 79 пикселей. The following code example specifies that the initial distance of the vertical splitter from the left edge of the container is 79 pixels. Также показаны другие основные свойства вертикального разделителя. Other basic properties of a vertical splitter are also shown. Этот пример является частью большого примера, приведенного для SplitContainer класса. This example is part of a larger example provided for the SplitContainer class.
Комментарии
Используйте SplitterDistance свойство, чтобы определить или задать расстояние в пикселях от разделителя до левого или верхнего края контейнера. Use the SplitterDistance property to determine or specify the distance in pixels of the splitter from the left or top edge of the container. Можно указать начальное расстояние и изменить расстояние во время разработки или во время выполнения. You can both specify an initial distance and change the distance at design time or run time. Если Orientation параметр имеет значение Horizontal , SplitterDistance вычисляется в пикселях от верхнего края SplitContainer . If Orientation is Horizontal , SplitterDistance is calculated in pixels from the top edge of the SplitContainer. Если Orientation параметр имеет значение Vertical , SplitterDistance вычисляется в пикселях от левого края SplitContainer . If Orientation is Vertical , SplitterDistance is calculated in pixels from the left edge of the SplitContainer.
Разделение строк с помощью метода String.Split на C# How to separate strings using String.Split in C#
Метод String.Split создает массив подстрок, разбивая входную строку по одному или нескольким разделителям. The String.Split method creates an array of substrings by splitting the input string based on one or more delimiters. Этот метод зачастую является самым простым способом разделить строку по границам слов. This method is often the easiest way to separate a string on word boundaries. Он также используется для разбиения строк по другим конкретным символам или строкам. It’s also used to split strings on other specific characters or strings.
Примеры C# в этой статье выполняются во встроенном средстве выполнения кода и на площадке Try.NET. The C# examples in this article run in the Try.NET inline code runner and playground. Нажмите на кнопку Выполнить, чтобы выполнить пример в интерактивном окне. Select the Run button to run an example in an interactive window. После выполнения кода вы можете изменить его и выполнить измененный код, снова нажав на кнопку Выполнить. Once you execute the code, you can modify it and run the modified code by selecting Run again. Либо в интерактивном окне выполняется измененный код, либо, если компиляция завершается с ошибкой, в интерактивном окне отображаются все сообщения об ошибках компилятора C#. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
Следующий код разбивает обычную фразу на массив строк для каждого слова. The following code splits a common phrase into an array of strings for each word.
Каждый экземпляр знака разделения создает значение в возвращаемом массиве. Every instance of a separator character produces a value in the returned array. Последовательные знаки разделения создают пустую строку в виде значения в возвращаемом массиве. Consecutive separator characters produce the empty string as a value in the returned array. В следующем примере показано создание пустой строки с использованием символа пробела в качестве разделителя. You can see how an empty string is created in the following example, which uses the space character as a separator.
Такое поведение упрощает работу с такими форматами, как файл данных с разделителями-запятыми (CSV), которые представляют табличные данные. This behavior makes it easier for formats like comma-separated values (CSV) files representing tabular data. Идущие подряд запятые представляют пустой столбец. Consecutive commas represent a blank column.
Чтобы исключить из возвращаемого массива все пустые строки, можно передать необязательный параметр StringSplitOptions.RemoveEmptyEntries. You can pass an optional StringSplitOptions.RemoveEmptyEntries parameter to exclude any empty strings in the returned array. Для более сложной обработки возвращенной коллекции можно использовать LINQ, чтобы управлять результирующей последовательностью. For more complicated processing of the returned collection, you can use LINQ to manipulate the result sequence.
String.Split может использовать несколько знаков разделения. String.Split can use multiple separator characters. В приведенном ниже примере в качестве знаков разделения используются пробелы, запятые, точки, двоеточия и символы табуляции, которые передаются в Split в массиве. The following example uses spaces, commas, periods, colons, and tabs as separating characters, which are passed to Split in an array . Цикл в конце кода отображает каждое из слов в возвращенном массиве. The loop at the bottom of the code displays each of the words in the returned array.
Последовательные экземпляры любого разделителя создают пустую строку в выходном массиве: Consecutive instances of any separator produce the empty string in the output array:
Извлечение подстрок из строки Extract substrings from a string
В этой статье рассматриваются различные методы извлечения частей строки. This article covers some different techniques for extracting parts of a string.
- Используйте метод Split, если нужные подстроки разделены символом-разделителем (или символами). Use the Split method when the substrings you want are separated by a known delimiting character (or characters).
- Регулярные выражения удобно использовать, когда строка соответствует фиксированному шаблону. Regular expressions are useful when the string conforms to a fixed pattern.
- Используйте сочетание методов IndexOf и Substring, если не хотите извлекать все подстроки из строки. Use the IndexOf and Substring methods in conjunction when you don’t want to extract all of the substrings in a string.
Метод String.Split String.Split method
String.Split предоставляет несколько перегрузок, которые позволяют разбить строку на группу подстрок, основанных на одном или нескольких указанных символах-разделителях. String.Split provides a handful of overloads to help you break up a string into a group of substrings based on one or more delimiting characters that you specify. Вы можете ограничить общее число подстрок в окончательном результате, обрезав пробелы в подстроках или исключив пустые подстроки. You can choose to limit the total number of substrings in the final result, trim white-space characters from substrings, or exclude empty substrings.
Ниже показаны три различные перегрузки String.Split() . The following examples show three different overloads of String.Split() . Первый пример вызывает перегрузку Split(Char[]) без передачи знаков разделения. The first example calls the Split(Char[]) overload without passing any separator characters. Если не указать символы-разделители, String.Split() будет использовать для разделения строки разделители по умолчанию, которые являются пробелами. When you don’t specify any delimiting characters, String.Split() uses default delimiters, which are white-space characters, to split up the string.
Как видите, символы-точки ( . ) содержатся в двух подстроках. As you can see, the period characters ( . ) are included in two of the substrings. Если вы хотите исключить символы-точки, добавьте символ-точку как дополнительный символ разделителя. If you want to exclude the period characters, you can add the period character as an additional delimiting character. В следующем примере показано, как это сделать. The next example shows how to do this.
Точки исчезли из подстрок, однако теперь появились две дополнительные пустые подстроки. The periods are gone from the substrings, but now two extra empty substrings have been included. Пустые подстроки представляют подстроку между словом и точкой после него. These empty substring represent the substring between the word and the period that follows it. Чтобы исключить из результирующего массива пустые подстроки, вызовите перегрузку Split(Char[], StringSplitOptions) и укажите StringSplitOptions.RemoveEmptyEntries для параметра options . To omit empty substrings from the resulting array, you can call the Split(Char[], StringSplitOptions) overload and specify StringSplitOptions.RemoveEmptyEntries for the options parameter.
Регулярные выражения Regular expressions
Если строка соответствует фиксированному шаблону, используйте регулярное выражение для извлечения и обработки ее элементов. If your string conforms to a fixed pattern, you can use a regular expression to extract and handle its elements. Например, если строки имеют форму «номер операнд номер«, тогда для извлечения и обработки элементов строки можно использовать регулярное выражение. For example, if strings take the form «number operand number«, you can use a regular expression to extract and handle the string’s elements. Пример: Here’s an example:
Шаблон регулярного выражения (\d+)\s+([-+*/])\s+(\d+) определяется следующим образом: The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:
Шаблон Pattern | Описание Description |
---|---|
(\d+) | Совпадение с одной или несколькими десятичными цифрами. Match one or more decimal digits. Это первая группа записи. This is the first capturing group. |
\s+ | Совпадение с одним или несколькими пробелами. Match one or more white-space characters. |
([-+*/]) | Совпадение со знаком арифметического оператора (+, -, *, или /). Match an arithmetic operator sign (+, -, *, or /). Это вторая группа записи. This is the second capturing group. |
\s+ | Совпадение с одним или несколькими пробелами. Match one or more white-space characters. |
(\d+) | Совпадение с одной или несколькими десятичными цифрами. Match one or more decimal digits. Это третья группа записи. This is the third capturing group. |
Вы также можете использовать регулярное выражение для извлечения подстрок из строки на основе шаблона, а не фиксированного набора символов. You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. Это распространенный сценарий, если происходит одно из следующих условий: This is a common scenario when either of these conditions occurs:
Один или несколько символов-разделителей не всегда служат разделителями в экземпляре String. One or more of the delimiter characters does not always serve as a delimiter in the String instance.
Последовательность и количество символов-разделителей являются изменяемыми или неизвестными. The sequence and number of delimiter characters is variable or unknown.
Например, метод Split нельзя использовать для разделения следующей строки, поскольку число символов \n (новая строка) является изменяемым и они не всегда являются разделителями. For example, the Split method cannot be used to split the following string, because the number of \n (newline) characters is variable, and they don’t always serve as delimiters.
Регулярное выражение может легко разделить эту строку, как показано ниже. A regular expression can split this string easily, as the following example shows.
Шаблон регулярного выражения \[([^\[\]]+)\] определяется следующим образом: The regular expression pattern \[([^\[\]]+)\] is defined like this:
Шаблон Pattern | Описание Description |
---|---|
\[ | Совпадение с открывающей скобой. Match an opening bracket. |
([^\[\]]+) | Совпадение с любым символом, который не является открывающей или закрывающей скобкой, один или несколько раз. Match any character that is not an opening or a closing bracket one or more times. Это первая группа записи. This is the first capturing group. |
\] | Совпадение с закрывающей скобкой. Match a closing bracket. |
Метод Regex.Split практически идентичен методу String.Split, за исключением того, что он разделяет строку на основе шаблона регулярного выражения, а не фиксированной кодировки. The Regex.Split method is almost identical to String.Split, except that it splits a string based on a regular expression pattern instead of a fixed character set. Например, в следующем примере метод Regex.Split используется для разделения строки, которая содержит подстроки, разделенные с помощью различных сочетаний дефисов и других символов. For example, the following example uses the Regex.Split method to split a string that contains substrings delimited by various combinations of hyphens and other characters.
Шаблон регулярного выражения \s-\s?[+*]?\s?-\s определяется следующим образом: The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:
Шаблон Pattern | Описание Description |
---|---|
\s- | Совпадение с пробелом, за которым следует дефис. Match a white-space character followed by a hyphen. |
\s? | Совпадение с нулем или одним символом пробела. Match zero or one white-space character. |
[+*]? | Совпадение с нулем или единичное появление символа + или *. Match zero or one occurrence of either the + or * character. |
\s? | Совпадение с нулем или одним символом пробела. Match zero or one white-space character. |
-\s | Совпадение с дефисом, за которым следует пробел. Match a hyphen followed by a white-space character. |
Методы String.IndexOf и String.Substring String.IndexOf and String.Substring methods
Если вам нужны все подстроки в строке, можете использовать один из методов сравнения строк, которые возвращают индекс начала сопоставления. If you aren’t interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. Затем для извлечения нужных подстрок можно будет вызвать метод Substring. You can then call the Substring method to extract the substring that you want. К методам сравнения строк можно отнести: The string comparison methods include:
IndexOf, возвращающий отсчитываемый от нуля индекс первого появления символа или строки в экземпляре строки. IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.
IndexOfAny, возвращающий отсчитываемый от нуля индекс в текущем экземпляре строки первого появления любого символа в массиве символов. IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.
LastIndexOf, возвращающий отсчитываемый от нуля индекс последнего появления символа или строки в экземпляре строки. LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.
LastIndexOfAny, возвращающий отсчитываемый от нуля индекс в текущем экземпляре строки последнего вхождения любого символа в массиве символов. LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.
В следующем примере метод IndexOf используется для поиска точек в строке. The following example uses the IndexOf method to find the periods in a string. После чего в нем используется метод Substring для возврата полных предложений. It then uses the Substring method to return full sentences.