Индексы массива
Массивом называется группа переменных, которые имеют одно и тоже имя, но различные индексы. Каждая переменная в этой группе называется элементом массива и характеризуется двумя атрибутами: своим местоположением внутри массива и значением. В зависимости от типа хранимых данных массивы могут быть любого типа- текстовые и числовые. В качестве индекса элемента массива могут применяться числа, переменные целого типа и арифметические выражения.
Массив — это набор однородных данных (чисел, символов, слов).
Оператор DIM определяет максимальное значение индексов переменных массива и отводит необходимую массиву память.
Для каждой переменной списка в скобках указывается верхняя граница индекса. Сами переменные записываются через запятую. Тип массива может быть любым допустимым в Basic.
Пример для одномерных массивов: DIM A(20), B(50), C(100)
Пример для двумерных массивов: DIM A(20,10), B(20,50), C(5,100)
Если переменная массива не была описана оператором DIM, то максимальное значение индексов принимается равным 10. Если значение индекса превышает максимальное установленное значение, то выдается сообщение «Subscript out of range». Минимальное значение индекса всегда равняется нулю, кроме того случая, когда оно изменяется с помощью оператора OPTION BASE.
Оператор DIM устанавливает все элементы описываемого массива равными нулю. Приставка RE переопределяет ранее определенный массив.
Индекс — это метка ячейки памяти которая используется для обращения к этой ячейке.
Переменные с индексами имеют одно и тоже имя, но разные индексы:
В программировании индекс пишется в скобках, в отличии от математической формы:
. Поскольку индексом может служить целочисленная переменная, в том числе и счетчик цикла, можно применять индексированные переменные вместе с циклом для ввода, сохранения и обработки группы значений.
Дополнительно:
Ссылаться на элементы массива можно по их индексам. У каждого элемента массива имеется уникальный числовой индекс, идентифицирующий его. Если массив одномерный, индекс элемента ѕ это номер его строки. Например, индекс элемента, находящегося в третьей строке одномерного массива, равен 3. 2
Элементы в двумерных массивах обозначаются двумя индексами. Первый индекс указывает положение элемента в строках, а второй индекс ѕ его положение в столбцах.
Например, индексами элемента, находящегося в третьей строке и четвертом столбце двумерного массива, будут 3,4. Подробнее об индексах элементов массивов см. описание функции ASUBSCRIPT().
Индекс (индексы) первого элемента массива всегда равен 1. Если массив двумерный, его также можно обозначить одним числом. Функция AELEMENT() возвращает одиночный индекс для пары строчного и столбцевого индексов, а функция ASUBSCRIPT() возвращает строчный и столбцевой индексы элемента из его одиночного индекса.
Переменные с индексами |
Описания необходимы для того, чтобы резервировать в памяти ЭВМ место для размещения элементов используемых массивов. Переменные с индексами (элементы массивов) можно использовать в программах так же, как и простые переменные соответствующего типа. Рассмотрим примеры составления программ с использованием массивов. Такого рода программы обычно являются циклическими: для того чтобы «перебрать» все элементы массива, необходимо многократно повторить однотипные действия. Пример 3.3.1. Составим программу отыскания наименьшего элемента в заданном одномерном массиве, содержащем я + 1 элементов а0, а, ап. Поскольку задачу должна решать ЭВМ, то алгоритм решения должен предусматривать ввод элементов массива в ее память. Предварительное описание алгоритма может быть таким: 1. Ввести элементы массива; 2. Отыскать в массиве наименьший элемент (т. е. найти его величину и номер); 3. Вывести найденные значения. Второй и третий шаги алгоритма уже представлены нами в виде последовательности предписаний (см. с. 70). Ясно, что для осуществления первого шага нужно сначала ввести значение я, а затем 104 для каждого I, изменяющегося от 0 до я, произвести ввод а;. Теперь мы можем оформить весь алгоритм в виде последовательности предписаний, отвечающих определенным ранее управляющим структурам. |
Файловая система — это определенный способ организации информации на внешних носителях и совокупность средств операционной системы, позволяющих работать с этой информацией.
Долговременное хранение информации на компьютере производится на устройствах внешней памяти. На персональных компьютерах основной вид внешней памяти — магнитный диск.
Устройство, которое производит запись и чтение информации с магнитного диска, называется дисководом или накопителем на магнитном диске.
Гибкие диски (дискеты) — сменные устройства, т. е. их можно менять в дисководе; винчестерский диск жестко вмонтирован в компьютер.
Файл — наименьший управляемый элемент файловой системы. Файл имеет имя и содержит в себе какую-то однотипную информацию, например текст документа, программу, числовой массив и пр.
Каждый каталог может содержать внутри себя множество файлов и вложенных каталогов (говорят — подкаталогов). Каталог самого верхнего уровня, который не вложен ни в какие другие, называется корневым каталогом.
путь к файлу — это последовательность, состоящая из имени накопителя и имен каталогов, начиная от корневого и заканчивая тем, в котором непосредственно хранится файл.
текущий каталог — это тот каталог, к содержимому которого в данный момент можно обращаться без продвижения вверх или вниз по дереву каталогов.
Как найти индекс элемента в массиве объектов?
Для поиска индекса элемента в массиве можно использовать методы indexOf (для первого вхождения) и lastIndexOf (для последнего вхождения). А как можно найти индекс в массиве объектов? Например индекс при первом вхождении нужного объекта? Например есть массив объектов:
let inputArr = [, , ];
Как получить индекс, где в свойстве name значение barry ? Если писать так:
inputArr.indexOf('barry');
то выведет -1 , а ожидаемое значение — 1 . Может циклом перебирать все значения? Может есть простые способы? orig post https://stackoverflow.com/q/8668174/6104996
Отслеживать
Алексей Шиманский
задан 19 дек 2017 в 16:00
Алексей Шиманский Алексей Шиманский
71.4k 12 12 золотых знаков 91 91 серебряный знак 180 180 бронзовых знаков
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
-
Использовать findIndex, которая в качестве параметра принимает callback функцию, в которой можно указать условия. Её можно использовать для поиска непримитивных типов (в т.ч. объектов), а также где можно/нужно задать более сложные условия, нежели просто значение. Если элемент не найден — возвращается -1 .
let searchName = 'barry'; let index = inputArr.findIndex(el => el.name === searchName);
- Пробежаться с помощью map , выбрав в массив нужные значения по указанному свойству
- Уже к этому массиву и применять indexOf
let searchName = 'barry'; let index = inputArr.map(el => el.name).indexOf(searchName);
Недостаток: map создает целый массив, в котором лежат эдементы с нужным property . Поэтому если в массиве, например 1000 элементов, то может сказаться на производительности.
Плюс: в отличие от findIndex — map поддерживают больше браузеров, т.к. это более старый метод для работы с массивами
function arrayObjectIndexOf(myArray, property, searchTerm) < for(let i = 0, len = myArray.length; i < len; i++) < if (myArray[i][property] === searchTerm) return i; >return -1; > let index = arrayObjectIndexOf(inputArr, 'name', searchName); console.log(index);
var index = _.findIndex(inputArr, ) // 1
Можно задать несколько условий (как и при использовании findIndex ), например:
let inputArr = [, , , , ]; let cond = ; var index = _.findIndex(inputArr, cond) console.log(index); // 3
Индексы и диапазоны
Диапазоны и индексы обеспечивают лаконичный синтаксис для доступа к отдельным элементам или диапазонам в последовательности.
Из этого руководства вы узнаете, как выполнять следующие задачи:
- Использовать этот синтаксис для диапазонов в последовательности.
- Неявно определяет объект Range.
- Проектировать начало и конец каждой последовательности.
- Составлять сценарии для типов Index и Range.
Поддержка языков для индексов и диапазонов
Диапазоны и индексы обеспечивают лаконичный синтаксис для доступа к отдельным элементам или диапазонам в последовательности.
Поддержка языков опирается на два новых типа и два новых оператора:
- System.Index представляет индекс в последовательности.
- Индекс из конечного оператора ^ , указывающий, что индекс относительно конца последовательности.
- System.Range представляет вложенный диапазон последовательности.
- Оператор .. диапазона, указывающий начало и конец диапазона в качестве операндов.
Начнем с правил для использования в индексах. Рассмотрим массив sequence . Индекс 0 совпадает с sequence[0] . Индекс ^0 совпадает с sequence[sequence.Length] . Выражение sequence[^0] создает исключение так же, как и sequence[sequence.Length] . Для любого числа n индекс ^n совпадает с sequence.Length — n .
string[] words = [ // index from start index from end "The", // 0 ^9 "quick", // 1 ^8 "brown", // 2 ^7 "fox", // 3 ^6 "jumps", // 4 ^5 "over", // 5 ^4 "the", // 6 ^3 "lazy", // 7 ^2 "dog" // 8 ^1 ]; // 9 (or words.Length) ^0
Последнее слово можно получить с помощью индекса ^1 . Добавьте следующий код после инициализации:
Console.WriteLine($"The last word is ");
Диапазон указывает начало и конец диапазона. Начало диапазона является включающим, но конец диапазона является исключающим, то есть начало включается в диапазон, а конец не включается. Диапазон [0..^0] представляет весь диапазон так же, как [0..sequence.Length] представляет весь диапазон.
Следующий код создает поддиапазон со словами «quick», «brown» и «fox». Он включает в себя элементы от words[1] до words[3] . Элемент words[4] в диапазон не входит.
string[] quickBrownFox = words[1..4]; foreach (var word in quickBrownFox) Console.Write($" < >"); Console.WriteLine();
Следующий код возвращает диапазон со словами «lazy» и «dog». Он включает элементы words[^2] и words[^1] . Конечный индекс words[^0] не включен. Добавьте также следующий код:
string[] lazyDog = words[^2..^0]; foreach (var word in lazyDog) Console.Write($" < >"); Console.WriteLine();
В следующих примерах создаются диапазоны, которые должны быть открыты для начала, конца или в обоих случаях:
string[] allWords = words[..]; // contains "The" through "dog". string[] firstPhrase = words[..4]; // contains "The" through "fox" string[] lastPhrase = words[6..]; // contains "the", "lazy" and "dog" foreach (var word in allWords) Console.Write($" < >"); Console.WriteLine(); foreach (var word in firstPhrase) Console.Write($" < >"); Console.WriteLine(); foreach (var word in lastPhrase) Console.Write($" < >"); Console.WriteLine();
Диапазоны или индексы можно также объявлять как переменные. Впоследствии такую переменную можно использовать внутри символов [ и ] :
Index the = ^3; Console.WriteLine(words[the]); Range phrase = 1..4; string[] text = words[phrase]; foreach (var word in text) Console.Write($" < >"); Console.WriteLine();
Следующий пример демонстрирует многие возможные причины для таких решений. Измените x , y и z и опробуйте различные комбинации. Поэкспериментируйте со значениями, у которых x меньше y , а y меньше, чем z для допустимых сочетаний. Добавьте в новый метод приведенный ниже код. Опробуйте различные комбинации:
int[] numbers = [..Enumerable.Range(0, 100)]; int x = 12; int y = 25; int z = 36; Console.WriteLine($" is the same as "); Console.WriteLine($" is the same as "); Console.WriteLine("numbers[x..y] and numbers[y..z] are consecutive and disjoint:"); Span x_y = numbers[x..y]; Span y_z = numbers[y..z]; Console.WriteLine($"\tnumbers[x..y] is through , numbers[y..z] is through "); Console.WriteLine("numbers[x..^x] removes x elements at each end:"); Span x_x = numbers[x..^x]; Console.WriteLine($"\tnumbers[x..^x] starts with and ends with "); Console.WriteLine("numbers[..x] means numbers[0..x] and numbers[x..] means numbers[x..^0]"); Span start_x = numbers[..x]; Span zero_x = numbers[0..x]; Console.WriteLine($"\t.. is the same as .."); Span z_end = numbers[z..]; Span z_zero = numbers[z..^0]; Console.WriteLine($"\t.. is the same as ..");
Индексы и диапазоны поддерживаются не только массивами. Можно также использовать индексы и диапазоны со строкой (Span или ReadOnlySpan ).
Преобразования выражений операторов неявного диапазона
При использовании синтаксиса выражения оператора диапазона компилятор неявно преобразует начальные и конечные значения в и Index из них создает новый Range экземпляр. В следующем коде показан пример неявного преобразования из синтаксиса выражения оператора диапазона и соответствующего явного альтернативного варианта:
Range implicitRange = 3..^5; Range explicitRange = new( start: new Index(value: 3, fromEnd: false), end: new Index(value: 5, fromEnd: true)); if (implicitRange.Equals(explicitRange)) < Console.WriteLine( $"The implicit range '' equals the explicit range ''"); > // Sample output: // The implicit range '3..^5' equals the explicit range '3..^5'
Неявные преобразования, отбрасываемые в Int32Index случае отрицательного ArgumentOutOfRangeException значения. Аналогичным образом Index конструктор создает ArgumentOutOfRangeException исключение при отрицательном значении value параметра.
Поддержка типов для индексов и диапазонов
Индексы и диапазоны предоставляют четкий и краткий синтаксис для доступа к одному элементу или диапазону элементов последовательности. Выражение индекса обычно возвращает тип элементов последовательности. Выражение диапазона обычно возвращает тот же тип последовательности, что и исходная последовательность.
Любой тип, который предоставляет индексатор с параметром Index или Range, явно поддерживает индексы или диапазоны соответственно. Индексатор, который принимает один параметр Range, может возвращать другой тип последовательности, например System.Span .
Производительность кода, использующего оператор range, зависит от типа операнда последовательности.
Временная сложность оператора range зависит от типа последовательности. Например, если последовательность является string или массивом, то результатом будет копия указанного раздела входных данных, поэтому временная сложность имеет значение O(N) (где N — это длина диапазона). С другой стороны, если это System.Span или System.Memory , результат ссылается на то же резервное хранилище, что означает отсутствие копии и использование операции O(1).
Помимо временной сложности, создаются дополнительные выделения и копии, влияющие на производительность. В коде, чувствительном к производительности, рекомендуется использовать Span или Memory в качестве типа последовательности, так как оператор range не предоставляет им выделений.
Тип является счетным, если у него есть свойство с именем Length или Count с доступным методом получения и типом возвращаемого значения int . Счетный тип, который не поддерживает индексы или диапазоны явным образом, может предоставить неявную поддержку для них. Дополнительные сведения см. в разделах о поддержке неявного индекса и неявного диапазона в примечании к предлагаемой функции. Диапазоны с поддержкой неявных диапазонов возвращают тот же тип последовательности, что и исходная.
Array реализует более сложное поведение. Одномерные массивы поддерживают как индексы, так и диапазоны. Многомерные массивы не поддерживают индексаторы или диапазоны. Индексатор для многомерного массива имеет не один, а несколько параметров. Массивы массивов также поддерживают и диапазоны и индексаторы. В следующем примере показано выполнение итерации для прямоугольного подраздела массива массивов. В этом примере выполняется итерация раздела в центре с исключением трех первых и последних строк, а также двух первых и последних столбцов из каждой выбранной строки:
int[][] jagged = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10,11,12,13,14,15,16,17,18,19], [20,21,22,23,24,25,26,27,28,29], [30,31,32,33,34,35,36,37,38,39], [40,41,42,43,44,45,46,47,48,49], [50,51,52,53,54,55,56,57,58,59], [60,61,62,63,64,65,66,67,68,69], [70,71,72,73,74,75,76,77,78,79], [80,81,82,83,84,85,86,87,88,89], [90,91,92,93,94,95,96,97,98,99], ]; var selectedRows = jagged[3..^3]; foreach (var row in selectedRows) < var selectedColumns = row[2..^2]; foreach (var cell in selectedColumns) < Console.Write($", "); > Console.WriteLine(); >
Во всех случаях оператор range для Array выделяет массив для хранения возвращаемых элементов.
Сценарии для индексов и диапазонов
Часто диапазоны и индексы используются для анализа отдельной части последовательности большего размера. В новом синтаксисе легче понять, о какой части последовательности идет речь. Локальная функция MovingAverage принимает Range в качестве аргумента. После этого метод перечисляет только это диапазон и вычисляет минимальное, максимальное и среднее значение. Попробуйте добавить в свой проект следующий код:
int[] sequence = Sequence(1000); for(int start = 0; start < sequence.Length; start += 100) < Range r = start..(start+10); var (min, max, average) = MovingAverage(sequence, r); Console.WriteLine($"From to : \tMin: ,\tMax: ,\tAverage: "); > for (int start = 0; start < sequence.Length; start += 100) < Range r = ^(start + 10)..^start; var (min, max, average) = MovingAverage(sequence, r); Console.WriteLine($"From to : \tMin: ,\tMax: ,\tAverage: "); > (int min, int max, double average) MovingAverage(int[] subSequence, Range range) => ( subSequence[range].Min(), subSequence[range].Max(), subSequence[range].Average() ); int[] Sequence(int count) => [..Enumerable.Range(0, count).Select(x => (int)(Math.Sqrt(x) * 100))];
Примечание по индексам диапазона и массивам
При получении диапазона из массива результатом является массив, скопированный из исходного массива, а не ссылающийся. Изменение значений в результирующем массиве не изменит значения в исходном массиве.
var arrayOfFiveItems = new[] < 1, 2, 3, 4, 5 >; var firstThreeItems = arrayOfFiveItems[..3]; // contains 1,2,3 firstThreeItems[0] = 11; // now contains 11,2,3 Console.WriteLine(string.Join(",", firstThreeItems)); Console.WriteLine(string.Join(",", arrayOfFiveItems)); // output: // 11,2,3 // 1,2,3,4,5
См. также
Совместная работа с нами на GitHub
Источник этого содержимого можно найти на GitHub, где также можно создавать и просматривать проблемы и запросы на вытягивание. Дополнительные сведения см. в нашем руководстве для участников.
Array. Index Of Метод
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Выполняет поиск указанного объекта и возвращает индекс первого найденного совпадения в одномерном массиве или диапазоне элементов массива.
Перегрузки
Выполняет поиск указанного объекта внутри всего одномерного массива и возвращает индекс его первого вхождения.
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон начинается с указанного индекса и заканчивается концом массива.
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон расширяется от указанного индекса заданного числа элементов.
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон начинается с указанного индекса и заканчивается концом массива.
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон расширяется от указанного индекса заданного числа элементов.
Выполняет поиск указанного объекта внутри всего одномерного массива и возвращает индекс его первого вхождения.
IndexOf(Array, Object)
Выполняет поиск указанного объекта внутри всего одномерного массива и возвращает индекс его первого вхождения.
public: static int IndexOf(Array ^ array, System::Object ^ value);
public static int IndexOf (Array array, object value);
public static int IndexOf (Array array, object? value);
static member IndexOf : Array * obj -> int
Public Shared Function IndexOf (array As Array, value As Object) As Integer
Параметры
Одномерный массив для поиска.
Объект, который требуется найти в array .
Возвращаемое значение
Индекс первого вхождения value в массиве array , если найден. В противном случае — нижняя граница массива минус 1.
Исключения
array имеет значение null .
Массив array является многомерным.
Примеры
В примере вызываются следующие три перегрузки IndexOf метода для поиска индекса строки в массиве строк:
- IndexOf(Array, Object), чтобы определить первое вхождение строки «the» в строковом массиве.
- IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки «the» в четвертом и последнем элементах массива строк.
- IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки «the» в строковом массиве из элемента, следующего за последним успешным совпадением в конце массива.
using namespace System; void main() < // Create a string array with 3 elements having the same value. array^ strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console::WriteLine("The array contains the following values:"); for (int i = strings->GetLowerBound(0); i GetUpperBound(0); i++) Console::WriteLine(" []: ", i, strings[i]); // Search for the first occurrence of the duplicated value. String^ searchString = "the"; int index = Array::IndexOf(strings, searchString); Console::WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array::IndexOf( strings, searchString, 4); Console::WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1); Console::WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings->GetUpperBound(0), index); > // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. let strings = [| "the"; "quick"; "brown"; "fox"; "jumps"; "over" "the"; "lazy"; "dog"; "in"; "the"; "barn" |] // Display the elements of the array. printfn "The array contains the following values:" for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do printfn $" []: " // Search for the first occurrence of the duplicated value. let searchString = "the" let index = Array.IndexOf(strings, searchString) printfn $"The first occurrence of \"\" is at index ." // Search for the first occurrence of the duplicated value in the last section of the array. let index = Array.IndexOf(strings, searchString, 4) printfn $"The first occurrence of \"\" between index 4 and the end is at index ." // Search for the first occurrence of the duplicated value in a section of the array. let position = index + 1 let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1) printfn $"The first occurrence of \"\" between index and index is at index ." // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. String[] strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console.WriteLine("The array contains the following values:"); for (int i = strings.GetLowerBound(0); i ]: ", i, strings[i]); // Search for the first occurrence of the duplicated value. string searchString = "the"; int index = Array.IndexOf(strings, searchString); Console.WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4); Console.WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1); Console.WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index); // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example Public Sub Main() ' Create a string array with 3 elements having the same value. Dim strings() As String = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >' Display the values of the array. Console.WriteLine("The array contains the following values:") For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0) Console.WriteLine(" []: ", i, strings(i)) Next ' Search for the first occurrence of the duplicated value. Dim searchString As String = "the" Dim index As Integer = Array.IndexOf(strings, searchString) Console.WriteLine("The first occurrence of """" is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4) Console.WriteLine("The first occurrence of """" between index 4 and the end is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in a section of the array. Dim position As Integer = index + 1 index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1) Console.WriteLine("The first occurrence of """" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index) End Sub End Module ' The example displays the following output: ' The array contains the following values: ' [ 0]: the ' [ 1]: quick ' [ 2]: brown ' [ 3]: fox ' [ 4]: jumps ' [ 5]: over ' [ 6]: the ' [ 7]: lazy ' [ 8]: dog ' [ 9]: in ' [10]: the ' [11]: barn ' The first occurrence of "the" is at index 0. ' The first occurrence of "the" between index 4 and the end is at index 6. ' The first occurrence of "the" between index 7 and index 11 is at index 10.
Комментарии
Этот метод выполняет поиск по всем элементам одномерного массива . value Чтобы определить, существует ли value в array , метод выполняет сравнение на равенство, вызывая метод каждого элемента Equals , пока не найдет совпадение. Это означает, что если элемент переопределяет Object.Equals(Object) метод, вызывается это переопределение.
Так как большинство массивов имеют нижнюю границу, равную нулю, этот метод обычно возвращает значение -1, если value не найден. В редких случаях, когда нижняя граница массива равна Int32.MinValue(0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).
Этот метод является операцией O( n ), где n — из Length array .
См. также раздел
Применяется к
IndexOf(Array, Object, Int32)
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон начинается с указанного индекса и заканчивается концом массива.
public: static int IndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int IndexOf (Array array, object value, int startIndex);
public static int IndexOf (Array array, object? value, int startIndex);
static member IndexOf : Array * obj * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer) As Integer
Параметры
Одномерный массив для поиска.
Объект, который требуется найти в array .
startIndex Int32
Начальный индекс поиска. Значение 0 (ноль) действительно в пустом массиве.
Возвращаемое значение
Индекс первого вхождения значения value в диапазоне элементов массива array , начинающемся с элемента с индексом startIndex и заканчивающемся последним элементом, если значение найдено; в противном случае нижняя граница массива минус 1.
Исключения
array имеет значение null .
startIndex находится вне диапазона допустимых индексов для array .
Массив array является многомерным.
Примеры
В примере вызываются следующие три перегрузки IndexOf метода для поиска индекса строки в массиве строк:
- IndexOf(Array, Object), чтобы определить первое вхождение строки «the» в строковом массиве.
- IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки «the» в четвертом и последнем элементах массива строк.
- IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки «the» в строковом массиве из элемента, следующего за последним успешным совпадением в конце массива.
using namespace System; void main() < // Create a string array with 3 elements having the same value. array^ strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console::WriteLine("The array contains the following values:"); for (int i = strings->GetLowerBound(0); i GetUpperBound(0); i++) Console::WriteLine(" []: ", i, strings[i]); // Search for the first occurrence of the duplicated value. String^ searchString = "the"; int index = Array::IndexOf(strings, searchString); Console::WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array::IndexOf( strings, searchString, 4); Console::WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1); Console::WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings->GetUpperBound(0), index); > // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. let strings = [| "the"; "quick"; "brown"; "fox"; "jumps"; "over" "the"; "lazy"; "dog"; "in"; "the"; "barn" |] // Display the elements of the array. printfn "The array contains the following values:" for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do printfn $" []: " // Search for the first occurrence of the duplicated value. let searchString = "the" let index = Array.IndexOf(strings, searchString) printfn $"The first occurrence of \"\" is at index ." // Search for the first occurrence of the duplicated value in the last section of the array. let index = Array.IndexOf(strings, searchString, 4) printfn $"The first occurrence of \"\" between index 4 and the end is at index ." // Search for the first occurrence of the duplicated value in a section of the array. let position = index + 1 let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1) printfn $"The first occurrence of \"\" between index and index is at index ." // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. String[] strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console.WriteLine("The array contains the following values:"); for (int i = strings.GetLowerBound(0); i ]: ", i, strings[i]); // Search for the first occurrence of the duplicated value. string searchString = "the"; int index = Array.IndexOf(strings, searchString); Console.WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4); Console.WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1); Console.WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index); // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example Public Sub Main() ' Create a string array with 3 elements having the same value. Dim strings() As String = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >' Display the values of the array. Console.WriteLine("The array contains the following values:") For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0) Console.WriteLine(" []: ", i, strings(i)) Next ' Search for the first occurrence of the duplicated value. Dim searchString As String = "the" Dim index As Integer = Array.IndexOf(strings, searchString) Console.WriteLine("The first occurrence of """" is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4) Console.WriteLine("The first occurrence of """" between index 4 and the end is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in a section of the array. Dim position As Integer = index + 1 index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1) Console.WriteLine("The first occurrence of """" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index) End Sub End Module ' The example displays the following output: ' The array contains the following values: ' [ 0]: the ' [ 1]: quick ' [ 2]: brown ' [ 3]: fox ' [ 4]: jumps ' [ 5]: over ' [ 6]: the ' [ 7]: lazy ' [ 8]: dog ' [ 9]: in ' [10]: the ' [11]: barn ' The first occurrence of "the" is at index 0. ' The first occurrence of "the" between index 4 and the end is at index 6. ' The first occurrence of "the" between index 7 and index 11 is at index 10.
Комментарии
Этот метод выполняет поиск одномерного массива от элемента по индексу startIndex до последнего элемента. Чтобы определить, существует ли value в array , метод выполняет сравнение на равенство, вызывая Equals метод каждого элемента, пока не найдет совпадение. Это означает, что если элемент переопределяет Object.Equals(Object) метод, вызывается это переопределение.
Так как большинство массивов имеют нижнюю границу, равную нулю, этот метод обычно возвращает значение -1, если value не найден. В редких случаях, когда нижняя граница массива равна Int32.MinValue(0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).
Если startIndex равно Array.Length, метод возвращает значение -1. Если startIndex значение больше Array.Length, метод создает исключение ArgumentOutOfRangeException.
Этот метод является операцией O( n ), где n — количество элементов от startIndex до конца array .
См. также раздел
- LastIndexOf
- Выполнение строковых операций без учета языка и региональных параметров в массивах
Применяется к
IndexOf(Array, Object, Int32, Int32)
Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого найденного совпадения. Диапазон расширяется от указанного индекса заданного числа элементов.
public: static int IndexOf(Array ^ array, System::Object ^ value, int startIndex, int count);
public static int IndexOf (Array array, object value, int startIndex, int count);
public static int IndexOf (Array array, object? value, int startIndex, int count);
static member IndexOf : Array * obj * int * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer, count As Integer) As Integer
Параметры
Одномерный массив для поиска.
Объект, который требуется найти в array .
startIndex Int32
Начальный индекс поиска. Значение 0 (ноль) действительно в пустом массиве.
Число искомых элементов.
Возвращаемое значение
Индекс первого вхождения значения value в диапазоне элементов массива array , начинающемся с индекса startIndex и заканчивающемся элементом с индексом startIndex + count — 1, если значение найдено. В противном случае нижняя граница массива минус 1.
Исключения
array имеет значение null .
startIndex находится вне диапазона допустимых индексов для array .
Значение параметра count меньше нуля.
startIndex и count не указывают допустимый раздел в array .
Массив array является многомерным.
Примеры
В примере вызываются следующие три перегрузки IndexOf метода для поиска индекса строки в массиве строк:
- IndexOf(Array, Object), чтобы определить первое вхождение строки «the» в строковом массиве.
- IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки «the» в четвертом и последнем элементах массива строк.
- IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки «the» в строковом массиве из элемента, следующего за последним успешным совпадением в конце массива. Чтобы определить значение аргумента count , он вычитает верхнюю границу массива из начального индекса и добавляет один.
using namespace System; void main() < // Create a string array with 3 elements having the same value. array^ strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console::WriteLine("The array contains the following values:"); for (int i = strings->GetLowerBound(0); i GetUpperBound(0); i++) Console::WriteLine(" []: ", i, strings[i]); // Search for the first occurrence of the duplicated value. String^ searchString = "the"; int index = Array::IndexOf(strings, searchString); Console::WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array::IndexOf( strings, searchString, 4); Console::WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1); Console::WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings->GetUpperBound(0), index); > // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. let strings = [| "the"; "quick"; "brown"; "fox"; "jumps"; "over" "the"; "lazy"; "dog"; "in"; "the"; "barn" |] // Display the elements of the array. printfn "The array contains the following values:" for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do printfn $" []: " // Search for the first occurrence of the duplicated value. let searchString = "the" let index = Array.IndexOf(strings, searchString) printfn $"The first occurrence of \"\" is at index ." // Search for the first occurrence of the duplicated value in the last section of the array. let index = Array.IndexOf(strings, searchString, 4) printfn $"The first occurrence of \"\" between index 4 and the end is at index ." // Search for the first occurrence of the duplicated value in a section of the array. let position = index + 1 let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1) printfn $"The first occurrence of \"\" between index and index is at index ." // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value. String[] strings = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >; // Display the elements of the array. Console.WriteLine("The array contains the following values:"); for (int i = strings.GetLowerBound(0); i ]: ", i, strings[i]); // Search for the first occurrence of the duplicated value. string searchString = "the"; int index = Array.IndexOf(strings, searchString); Console.WriteLine("The first occurrence of \"\" is at index .", searchString, index); // Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4); Console.WriteLine("The first occurrence of \"\" between index 4 and the end is at index .", searchString, index); // Search for the first occurrence of the duplicated value in a section of the array. int position = index + 1; index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1); Console.WriteLine("The first occurrence of \"\" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index); // The example displays the following output: // The array contains the following values: // [ 0]: the // [ 1]: quick // [ 2]: brown // [ 3]: fox // [ 4]: jumps // [ 5]: over // [ 6]: the // [ 7]: lazy // [ 8]: dog // [ 9]: in // [10]: the // [11]: barn // The first occurrence of "the" is at index 0. // The first occurrence of "the" between index 4 and the end is at index 6. // The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example Public Sub Main() ' Create a string array with 3 elements having the same value. Dim strings() As String = < "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "the", "barn" >' Display the values of the array. Console.WriteLine("The array contains the following values:") For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0) Console.WriteLine(" []: ", i, strings(i)) Next ' Search for the first occurrence of the duplicated value. Dim searchString As String = "the" Dim index As Integer = Array.IndexOf(strings, searchString) Console.WriteLine("The first occurrence of """" is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in the last section of the array. index = Array.IndexOf(strings, searchString, 4) Console.WriteLine("The first occurrence of """" between index 4 and the end is at index .", searchString, index) ' Search for the first occurrence of the duplicated value in a section of the array. Dim position As Integer = index + 1 index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1) Console.WriteLine("The first occurrence of """" between index and index is at index .", searchString, position, strings.GetUpperBound(0), index) End Sub End Module ' The example displays the following output: ' The array contains the following values: ' [ 0]: the ' [ 1]: quick ' [ 2]: brown ' [ 3]: fox ' [ 4]: jumps ' [ 5]: over ' [ 6]: the ' [ 7]: lazy ' [ 8]: dog ' [ 9]: in ' [10]: the ' [11]: barn ' The first occurrence of "the" is at index 0. ' The first occurrence of "the" between index 4 and the end is at index 6. ' The first occurrence of "the" between index 7 and index 11 is at index 10.
Комментарии
Этот метод выполняет поиск элементов одномерного массива от startIndex до startIndex плюс count минус 1, если count больше 0. Чтобы определить, существует ли value в array , метод выполняет сравнение на равенство, вызывая Equals метод каждого элемента, пока не найдет совпадение. Это означает, что если элемент переопределяет Object.Equals метод, вызывается это переопределение.
Так как большинство массивов имеют нижнюю границу, равная нулю, этот метод обычно возвращает -1, если value не найден. В редких случаях, когда нижняя граница массива равна Int32.MinValue (0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).
Если startindex равно Array.Length, метод возвращает значение -1. Если startIndex значение больше Array.Length, метод создает исключение ArgumentOutOfRangeException.
Этот метод является операцией O( n ), где n имеет значение count .
См. также раздел
- LastIndexOf
- Выполнение строковых операций без учета языка и региональных параметров в массивах