【问题标题】:How to parse for integers in individual elements in an array如何解析数组中单个元素中的整数
【发布时间】:2016-03-04 04:41:04
【问题描述】:

我希望能够从一个数组中读取一组特定的行,这些行与我在另一个数组中的某个名称相关

例如:

在名称数组中,我将“Ben”存储为名称,我想查看另一个数组是否也包含名称“Ben”,如果包含,它将添加“Ben”所在的每一行的分数提到

其他数组:

“本得到 5” “纳什得了 6” “本有 4 个” “乔什得到 1”

所以它只会将 5 和 4 相加得到 9

然后程序会将计算出的数字保存到一个列表中。

For Each n As String In commonNames 'for the example the commonNames array contains Ben"
                If names.Contains(n) Then
                    'add each of their scores and divide by how many their are
                End If
            Next
            Console.ReadLine()
            For Each n As String In originames
                'add each score to the user and divide by 1

任何帮助将不胜感激 :)

【问题讨论】:

  • 这是continuation,是吗? ;)
  • 是的,我基本上看一个数组是否包含与另一个数组相同的名称,并将其与另一个数组中的元素进行比较,每次在一行中提到“Ben”时,该行的分数是加在一起
  • 我认为最好在这里有一个描述你的对象的类,比如Person

标签: arrays vb.net integer


【解决方案1】:
Dim data = {"Ben got 5", "Nash got 6", "Ben got 4", "Josh got 1", "Ziggy got 42"}
Dim names = {"Ben", "Ziggy"}
Dim results(names.Length - 1) As Int32

For Each item In data
    For n As Int32 = 0 To names.Length - 1
        ' see if this item starts with name data
        If item.StartsWith(names(n)) Then
            ' if so, parse out the value
            Dim parts = item.Split(" "c)
            results(n) += Int32.Parse(parts(parts.Length - 1))
            Exit For
        End If
    Next
Next

' show contents of parallel arrays:
For n As Int32 = 0 To names.Length - 1
    Console.WriteLine("{0} total = {1}", names(n), results(n))
Next

结果:

本总 = 9
Ziggy 总数 = 42

如果数据末尾可能包含非数字,请使用 TryParse 代替。


基于一系列相关问题,您应该认真考虑使用一些允许您将相关数据存储在一起的类。而不是一个数组中的名称和另一个数组中的分数/计数,类有助于将所有内容放在一起。请参阅:此答案中的Five Minute Intro To Classes and Lists

使用简单的NameValuePair 实用程序类from this answer 代码实际上变得更简单(仅一个循环)并且名称和计数保持在一起:

Dim np As NameValuePair                       ' scratch var
Dim players As New List(Of NameValuePair)     ' list

' add the names you are looking for to
' the list with 0 Score/Count
' not needed if they are in the list from code upstream
For Each n As String In names
    players.Add(New NameValuePair(n, 0))
Next

For Each item In data
    Dim parts = item.Split(" "c)
    ' is there a player name for this one?
    np = players.FirstOrDefault(Function(w) w.Name = parts(0))

    If np IsNot Nothing Then
        np.Value += Int32.Parse(parts(parts.Length - 1))
    End If
Next

' the data is together: print it
For Each np In players
    Console.WriteLine("Name: {0} has {1} apples", np.Name, np.Value)
Next

【讨论】:

  • 感谢冥王星!但是除了将它们存储到数组之外,您如何将它们存储到列表中?
  • I 将保留它,以便值与名称的顺序相同,然后执行:Dim resultList As New List(of Int32)(results) 否则您可以最终得到与分数无关的名字。但如前所述,一个不错的现代 OOP 类对于您正在做的任何事情都会更好地工作 - 太多的并行数组。 A simple NameValuePair 可能有助于将名称与分数/计数保持一致
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 2018-05-04
  • 2022-11-29
  • 2015-11-14
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
相关资源
最近更新 更多