如何在数组VB.Net中指示数字出现的位置

时间:2018-06-26 10:26:39

标签: vb.net

搜索按钮:此按钮应确定输入了文本框中指定数字的次数。附加指示发生位置

这是我编写代码的方式,但是没有显示出事件在数组中的位置:

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim count As Integer = 0
    Dim value As Integer = txbValues.Text()
    For Each num As Integer In numbers
        If num = value Then count = count + 1
    Next
    txbOccurances.Text = count

    Dim index0 As Integer = Array.IndexOf(numbers, value)
    Dim index1 As Integer = Array.LastIndexOf(numbers, value)


    txbPosition.Text = index0 & " " & index1
End Sub

我要搜索的数组是number(4)。该程序应如下所示:

enter image description here

3 个答案:

答案 0 :(得分:1)

您当前的代码实际上适用于您给出的示例。但问题是,只有在数组中出现两次或更少次数时,它才有效。如果超出此范围,它将仅找到第一个和最后一个出现。

您可以维护所有找到的包含匹配编号的索引的列表-您可以在为测试值而进行的现有循环中执行此操作。

这是示例代码,将在控制台应用程序中运行,以演示该想法...您可以用用户的实际输入替换“数字”数组和“值”整数,并用代码替换控制台写入内容来填充您的文本框。

Dim numbers() as Integer = {1, 1, 4, 5, 2, 1} 'array to be searched
Dim value As Integer = 1 'number to search for

Dim index = 0
Dim indexes As New List(Of Integer)

For Each num As Integer In numbers
    If num = value Then 
        indexes.Add(index)
    End If
    index += 1
Next

Console.WriteLine("Occurences: " & indexes.Count)
Console.Write("Indexes: ")

For Each ind as Integer In indexes
    Console.Write(ind & " ")
Next

这将输出:

Occurences: 3
Indexes: 0 1 5

答案 1 :(得分:1)

通过Array.IndexOf方法,您可以指定从其开始搜索的索引,因此,每次找到事件时,都可以从下一个索引重新开始搜索:

Private Function GetIndexes(array As Integer(), value As Integer) As Integer()
    Dim indexes As New List(Of Integer)
    Dim startIndex = 0
    Dim index As Integer

    Do
        index = System.Array.IndexOf(array, value, startIndex)

        If index = -1 Then
            'No more occurrences found.
            Exit Do
        End If

        indexes.Add(index)

        startIndex = index + 1
    Loop Until startIndex = array.Length

    Return indexes.ToArray()
End Function

例如

Dim array = {0, 1, 2, 3, 1, 5, 6, 7, 1, 9}
Dim value = 1

Dim indexes = GetIndexes(array, value)

Console.WriteLine("Occurrences: " & indexes.Length)
Console.WriteLine("Indexes: " & String.Join(" ", indexes))

答案 2 :(得分:0)

我对ADyson程序的变化:

    Dim numbers() As Integer = {1, 1, 4, 5, 2, 1} 'array to be searched
    Dim value As Integer = 1 'number to search for

    Dim index As New Dictionary(Of Integer, Integer)

    For Each num As Integer In numbers
        If Not index.ContainsKey(num) Then
            index.Add(num, 1)
        Else
            index(num) += 1
        End If
    Next

    Console.WriteLine("Occurences: " & index(value))
    Console.Write("Indexes: ")

    For i = 0 To numbers.Count - 1
        If numbers(i) = value Then
            Console.Write(i & " ")
        End If
    Next