【问题标题】:Reading integers from a text file only and separating仅从文本文件中读取整数并分离
【发布时间】:2015-02-10 22:07:05
【问题描述】:

我创建了一个程序,该程序仅从包含字符串的文本文件以及列表框中成功读取整数。例如: 文本文件包含:

  • 泰勒 7
  • 丹尼尔 2
  • 迈克 6
  • 罗里 9

然后列表框将显示:7269。 但是我计划将这些数字从最高到最低排序(反之亦然),为了做到这一点,我想尝试将每个数字存储在列表框中的新行上,但我不确定如何完成此操作。 我用来读取整数的代码是:

    Dim intOnly As String = IO.File.ReadAllText(File_1)

    Dim intValue As String = String.Empty

    For Each c As Char In intOnly

        If IsNumeric(c) Then

            intValue += c

        End If

    Next

    ListBox3.Items.Add(intValue)
End Sub

【问题讨论】:

  • 不要在数学中使用字符串!
  • 点赞:If IsNumeric(c) Then ListBox3.Items.Add(c) ?
  • 呵呵,我是个新手,但字符串不会更好,因为它将整数与字符串分开?
  • 我想如果你想保留数字并且不想把它们加起来那可以开始
  • @Index 几乎适用于我想要做的事情!问题是虽然它使 '10' 在不同的行上显示为 '1' 和 '0',是否有解决方法?

标签: vb.net listbox integer streamreader


【解决方案1】:

试试这个:

Private Sub test()
    Dim sr As New System.IO.StreamReader("file.txt")
    Dim LofInt As New List(Of String)

    While sr.Peek <> -1
        Dim line As String = sr.ReadLine
        Dim intValue As String = String.Empty

        For Each c As Char In line
            If IsNumeric(c) Then
                intValue += c
            End If
        Next

        LofInt.Add(intValue)
    End While

    sr.Close()

    LofInt.Sort()
    For Each i In LofInt
        ListBox1.Items.Add(i)
    Next

End Sub

所以基本上我们的工作是: 我们逐行读取文件并存储数值。在每一行之后,我们将我们拥有的内容添加到列表中。 之后,我们使用该列表的函数对“数字”(仍然是字符串,所以我们应该说文本)进行排序并将它们添加到您的列表框

【讨论】:

  • 正如您在下面的答案中看到的,解决此问题的方法不止一种。我试图靠近您的方法,因为它可能更容易理解并且可能适用于您的程序。尝试从文本中过滤数字时 - 逐字符执行此字符是错误的方式(在大多数情况下)。即使您在此处使用此解决方案,也请查看其他解决方案并尝试了解它们的作用。
【解决方案2】:

利用ListBox.DataSource 属性和数组,您可以在新行中显示每个数字。

例如:

aLstSrc = New Integer(2) {}
aLstSrc(0) = 1
aLstSrc(1) = 2
aLstSrc(2) = 3

ListBox1.DataSource = aLstSrc

在您的示例中,您应该启动数组并在 For Each 循环中填充。

您可以将数组创建为 String 或 Integer,但如果您需要对数据执行进一步处理,Integer 应该是最佳选择。

另请参阅此以获得有关将文本文件处理为数组/列表的更多信息:VB.NET - Reading a text file containing tab-separated integers/doubles and storing them in arrays

【讨论】:

    【解决方案3】:

    试试这样的:

        Dim values As New List(Of Integer)
    
        Dim File_1 As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.Txt")
        For Each line As String In System.IO.File.ReadLines(File_1)
            Dim m As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(line, "\d+")
            If m.Success Then
                values.Add(Convert.ToInt32(m.Value))
            End If
        Next
    
        values.Sort()
        values.Reverse()
        ListBox3.DataSource = values
    

    【讨论】:

    • 如果你的文件不打算改变它的格式,那么像分割函数这样简单的东西应该可以工作。您可以将行拆分并存储到一个数组中,然后通过一个非数字方法检索第二个索引。如果我是你,我会将所有这些都包含在一个 try catch 块中。
    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多