查找字符串中不存在的数字

Find the numbers that do not exist in a String

问题如下:我有一组从1到80的数字。
Textbox1.Text 中,我有以下数字:

TextBox1.Text = "1,4,5,6,7,8,12,13,14,15,16,17,18,19,20,21,22,23,25,28,29,31,33,
                 34,35,36,37,39,40,41,45,46,47,48,49,51,53,54,55,57,59,60,61,62,
                 63,64,66,67, 68,69,70,71,72,73,75,76,77,78,79,80"

如何在 TextBox2.Text 中显示 1 到 80 中不在 TextBox1 中的数字?

TextBox2.Text = "2,3,9,10,11 and so on..."

考虑到问题引用了数字,因此结果值可能会在某处用作实际数字(而不仅仅是数字的字符串表示),您可以:

  • List(Of Integer)
  • 中的源字符串中提取值
  • 创建一个 List(Of Integer) 并使用 Enumerable.Range
  • 使用与源数字的最大值相对应的多个元素进行初始化
  • 使用 Enumerable.Except
  • 使用部分号码过滤完整号码列表
  • 如果需要,将生成的 List(Of Integer) 转换为以逗号分隔的值字符串。

:
我假设源字符串已经过验证。如果不是,请使用 Integer.TryParse instead of Integer.Parse. A related sample code is in this (so very similar) question.


Dim BaseNumbers As List(Of Integer) = 
    txtInput.Split(","c).Select(Function(n) Integer.Parse(n)).OrderBy(Function(n) n).ToList()

'Get the List of missing numbers in the source range of values
Dim ResultList As List(Of Integer) = 
    Enumerable.Range(1, BaseNumbers.Max()).Except(BaseNumbers).ToList()

'Convert to string the resulting List
Dim resultString = String.Join(",", ResultList)

这里有两个不使用 LINQ 的例子。

这个使用字典和列表:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim n As Integer
    Dim present As New Dictionary(Of Integer, Boolean)
    For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        If Integer.TryParse(strValue, n) Then
            present.Add(n, True)
        End If
    Next

    Dim notPresent As New List(Of Integer)
    For i As Integer = 1 To 80
        If Not present.ContainsKey(i) Then
            notPresent.Add(i)
        End If
    Next

    TextBox2.Text = String.Join(",", notPresent.ToArray)
End Sub

这个简单地使用了两个列表:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim n As Integer
    Dim present As New List(Of Integer)
    For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        If Integer.TryParse(strValue, n) Then
            present.Add(n)
        End If
    Next
    present.Sort() ' optional; if you need these sorted for something else

    Dim notPresent As New List(Of Integer)
    For i As Integer = 1 To 80
        If present.IndexOf(i) = -1 Then
            notPresent.Add(i)
        End If
    Next

    TextBox2.Text = String.Join(",", notPresent.ToArray)
End Sub