VB如何根据索引范围获取子数组?有无类似其他语言的切片语法?
VB中的数组切片实现方法
VB并没有像部分语言那样提供this_array[starting_index..ending_index]这种简洁的原生数组切片语法,但可以通过以下方式实现类似的功能:
VB6
VB6没有内置的数组切片函数,需要手动编写函数来提取指定索引范围的元素:
Function GetArraySlice(arr As Variant, startIdx As Integer, endIdx As Integer) As Variant Dim resultCount As Integer resultCount = endIdx - startIdx + 1 Dim resultArr() As Variant ReDim resultArr(resultCount - 1) Dim i As Integer For i = startIdx To endIdx resultArr(i - startIdx) = arr(i) Next i GetArraySlice = resultArr End Function
调用示例:
Dim sourceArray() As Variant sourceArray = Array("a", "b", "c", "d", "e") Dim slicedArr() As Variant slicedArr = GetArraySlice(sourceArray, 1, 3) ' 获取索引1到3的元素,结果为("b","c","d")
VB.NET
VB.NET有更便捷的实现方式,常用的两种方法如下:
方法一:使用Array.Copy
Dim sourceArray As Integer() = {10, 20, 30, 40, 50} Dim startIndex As Integer = 2 Dim endIndex As Integer = 4 Dim sliceLength As Integer = endIndex - startIndex + 1 Dim slicedArray(sliceLength - 1) As Integer Array.Copy(sourceArray, startIndex, slicedArray, 0, sliceLength)
方法二:使用LINQ(需导入System.Linq)
Imports System.Linq Dim sourceArray As String() = {"apple", "banana", "cherry", "date"} Dim slicedArray As String() = sourceArray.Skip(1).Take(2).ToArray() ' 跳过第1个元素后取2个,结果为("banana","cherry")
内容的提问来源于stack exchange,提问作者Nocxy
相关产品推荐
相关产品推荐

