首页 > 解决方案 > 通过具有多个重复值的值在数组中搜索索引

问题描述

我有一些这样的代码

dim pos, arr, val
arr = Array("a", "b", "c", "d")
val = "b"

pos = Application.Match(val, arr, False)
If Not IsError(pos) Then
MsgBox pos
End If

这很好用

除了现在我需要做一些更复杂的事情如果我有一个像

arr = Array("a", "b", "b", "b","c","c","d")

我想返回数组中所有出现该值的索引。

我知道您可以使用 isinarray 但这只会告诉您该值是否存在,我需要知道数组中的哪些索引包含指定的值。

有没有办法在不循环整个数组的情况下做到这一点?

标签: arraysexcelvbaindexing

解决方案


您必须执行一个包含两个循环(如 a )的函数,并将要返回的位置for存储在其他数组 ( ) 中。indexes它可能看起来像这样的伪代码:

function(int[] getIndexes -> { char[] array, char value }) 
    int indexes_found -> 0

    // Supposing that the array position starts at zero. 
    // This is to know the size of idexes array.
    for(int array_pos -> 0, array_pos < sizeof(array), array_pos -> array_pos + 1)

        if(value isEqualsTo array[array_pos])
            indexes_found -> indexes_found + 1
        end(if)
    end(for)

    // The array to be returned will have a size of idexes_found value.
    int[idexes_found] indexes

    // This is to get the next position in indexes array.
    // Remember, size ofindexes is less than or equals to size of array
    int index_pos -> 0

    for(int array_pos -> 0, array_pos < sizeof(array), array_pos -> array_pos + 1)
        if(value isEqualsTo array[array_pos])
            idexes[index_pos] -> array_pos
            index_pos -> index_pos + 1
        end(if)
    end(for)

    return idexes
end(function)

输入/输出示例:

输入:

char[5] letters -> { 'a', 'b', 'c', 'a', 'b' }
char value -> 'b'

int[] indexes -> getIndexes(letters, value)

输出:

indexes -> { 1, 4 }

希望对你有所帮助。

问候。


推荐阅读