如何计算文本框中的数字

时间:2018-12-24 15:41:57

标签: vb.net

我有以下数字字符串:

Textbox1.text / or Textbox1.Line= 1,2,3,19,29,78,48,39,40,51,53,54,69,70,71,73
Textbox2.text= / or Textbox2.Line=  1,9,3,31,29,78,45,39,40,51,59,54,69,70,71,73
textbox3.text= / or TextBox3.Line= 11,4,3,31,29,78,45,39,40,53,59,54,6974,75,76
    and Others ...

如何进行计数,以显示文本框中有1到10之间的数字,有11-20之间的数字,有31-40之间的数字,依此类推。示例:在第1行上-我们将有3个小数字,从1到10(1,2,3)。

2 个答案:

答案 0 :(得分:1)

您可以轻松地将包含逗号分隔的整数列表的字符串转换为这样的字符串数组

Dim s = "1,2,3,19,29,78,48,39,40,51,53,54,69,70,71,73"
Dim parts = s.Split(","c)

然后将字符串数组转换为整数列表

Dim numbers = New List(Of Integer)
For Each p As String In parts
    Dim i As Integer
    If Integer.TryParse(p, i) Then
        numbers.Add(i)
    End If
Next

现在是计数部分。使用LINQ,您可以编写

Dim tens = From n In numbers
            Group n By Key = (n - 1) \ 10 Into Group
            Order By Key
            Select Text = $"{ 10 * Key + 1} - {10 * Key + 10}", Count = Group.Count()

For Each x In tens
    Console.WriteLine($"{x.Text} --> {x.Count}")
Next

打印

1 - 10 --> 3
11 - 20 --> 1
21 - 30 --> 1
31 - 40 --> 2
41 - 50 --> 1
51 - 60 --> 3
61 - 70 --> 2
71 - 80 --> 3

答案 1 :(得分:1)

为此,您将必须将字符串拆分为数组或列表,然后将数组或列表中的值与所需的数字进行比较。像这样

 Dim arr1 As New List (Of String)
 arr1.AddRange(Split (TextBox1.Text, ","))
 Dim final As String
 Dim count As Integer = 0
 For Each item As String In arr1
    If CInt(item) >= 1 And  CInt(item) <= 10 Then
           count+=1
      'replace 10 with the maximum number you want and 1 with the minimum number. 
           final&=item & " "
      End If
 Next
 Msgbox("There are " & count & "numbers" & final)