gpt4 book ai didi

vb.net - 在数组中查找连续的数字

转载 作者:行者123 更新时间:2023-12-04 06:09:21 25 4
gpt4 key购买 nike

我需要在数组中找到连续的数字并返回一个字符串,该字符串告诉范围和不构成范围的数字。

我发现了一些已经问过的问题,但没有一个在 VB.Net 中:

Add to array consecutive numbers



如果数字数组看起来像 {11,12,67,68,69,70,92,97}那么返回的字符串应该是 11,12, 67 through 70, 92 and 97 的形式.

这不是家庭作业;对于包含统计数据的 Word 文档,我需要此功能。

最佳答案

直接进入回复窗口,所以几乎可以肯定有一三个错误:

Public Class Range

Public Shared Function PrintRanges(ByVal numbers() As Integer) As String
Dim buffer As New List(Of Range)()
Dim CurrentRange As Range = Nothing

For Each i As Integer in numbers ' you may want to add a .OrderBy() here
If CurrentRange IsNot Nothing AndAlso i - 1 = CurrentRange.EndValue Then
CurrentRange.Increase()
Else
CurrentRange = New Range(i)
buffer.Add(CurrentRange)
End If
Next i

'Got a little lazy for this line - it still does a ", " rather than " and " for the final delimiter. Simple code to fix it, just tedious.
Return String.Join(", ", buffer.Select(Function(r) r.ToString()).ToArray())
End Function

Private Sub New(ByVal InitialValue As Integer)
EndValue = IntialValue
Length = 1
End Sub

'For completeness, these two properties should be made read only outside the class, but the private constructor makes that largely moot
Public Property EndValue As Integer
Public Property Length As Integer

Public Sub Increase()
Length += 1
EndValue += 1
End Sub

Public Overrides Function ToString() As String
If Length == 1 Then Return EndValue.ToString()
If Length == 2 Then Return (EndValue -1).ToString() & "," & LastValue.ToString()
Return (EndValue - Length).ToString() & " through " & EndValue.ToString()
End Function

End Class

关于vb.net - 在数组中查找连续的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7949600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com