【问题标题】:how to Find and count duplicate numbers in a string array in vb.net?如何在 vb.net 的字符串数组中查找和计算重复数字?
【发布时间】:2015-08-13 08:58:06
【问题描述】:

如何统计vb.net中字符串或整数数组中存在的重复数字?

Dim a as string = "3,2,3"

从上面的“a”变量中,我希望将“3”计数为 2(我的意思是 3 存在 2 次)和“2”作为“1”。那么我如何在 vb.net 中制作它??????

其实我会从sql数据库中得到上面的字符串“a”。所以我不知道那里有哪些数字。这就是我在这里问的原因。

【问题讨论】:

  • 如图,a是字符串,不是字符串数组
  • 是的,兄弟,它是一个字符串。但是有没有办法找到它的计数??? @Plutonix
  • 你是否也在寻找这个最短的代码:-)
  • @Shar1er80 绝对...... :)

标签: arrays vb.net


【解决方案1】:

您已经有一些不错的答案可供选择,但我认为您会对单线解决方案感兴趣。

Module Module1
    Sub Main()
        Dim str() As String = "1,2,1,2,3,1,0,1,4".Split(","c)
        str.Distinct().ToList().ForEach(Sub(digit) Console.WriteLine("{0} exists {1}", digit, str.Count(Function(s) s = digit)))
        Console.ReadLine()
    End Sub
End Module

解释发生了什么:

  • str.Distinct() - 返回数组中所有唯一项的 IEnumerable 对象
  • .ToList() - 将 IEnumerable 对象转换为 List<T>
  • .ForEach() - 遍历List<T>
    • Sub(digit) - 定义一个 Action 委托以在每个元素上执行。在每次迭代期间,每个元素都被命名为 digit。
    • 你应该知道Console.WriteLine()在做什么
    • str.Count() - 每次出现一个满足条件的数字
      • Function(s) s = digit - 定义一个 Func 委托,它将计算数组中每个出现的数字。 str() 中的每个元素在 Count 迭代期间存储在变量 s 中,如果它与来自 Sub(digit) 的数字变量匹配,它将被计数

结果:

1 exists 4
2 exists 2
3 exists 1
0 exists 1
4 exists 1

【讨论】:

    【解决方案2】:

    如果你有一个像你的例子一样的字符串,首先根据你的分隔符拆分它;那么你可以使用 GroupBy Linq 查询:

    Dim source = "3,2,3".Split(","c)
    
    Dim query = From item In source
                Group By item Into Count()
    
    For Each result In query
        Console.WriteLine (result)
    Next
    
    ' output
    ' { item = 3, Count = 2 }
    ' { item = 2, Count = 1 }
    

    【讨论】:

      【解决方案3】:

      另一个使用Dictionary的选项:

          Dim a As String = "3,2,3"
      
          Dim counts As New Dictionary(Of String, Integer)
          For Each value As String In a.Split(",")
              If Not counts.ContainsKey(value) Then
                  counts.Add(value, 1)
              Else
                  counts.Item(value) = counts.Item(value) + 1
              End If
          Next
      
          For Each kvp As KeyValuePair(Of String, Integer) In counts
              Debug.Print("Value: " & kvp.Key & ", Count: " & kvp.Value)
          Next
      

      输出:

      Value: 3, Count: 2
      Value: 2, Count: 1
      

      【讨论】:

      • 我喜欢你回答得更好,假设字符串代表数据并且数字之间会有逗号
      【解决方案4】:
      Dim count2 as integer = 0
      Dim count3 as integer = 0    
      For Each c As Char in a
       if c = "3"
            count3 += 1
       else if c = "2"
            count2 += 1
       end if
      Next
      console.writeline(count2)
      console.writeline(count3)
      

      我猜,这听起来有点像家庭作业

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2016-05-20
        • 2011-11-05
        • 2018-01-21
        • 2021-12-03
        相关资源
        最近更新 更多