字符串搜索数字计数程序

时间:2016-01-28 00:57:15

标签: vb.net

大家好我是vb.net的初学者

我需要帮助制作一个表格,我们输入一个字符串,说" abc123"按下按钮,消息框显示总位数(0-9),数字的平均值,最小数量和最大数量。在这种情况下,在字符串" abc123"有3个数字,平均值是2,min是1,最大值是3.我需要使用a进行下一个循环,不能使用数组。如何搜索字符串并将字符中的数字分开? 到目前为止,我有:

Dim str1 as String = txt1.Text
Dim intCounter As Integer = 0
Dim intTotal As Integer = 0

For intCounter = 0 to str1.IndexOf(???)
    intTotal += intCounter
Next

谢谢!

修改

因为我无法使用For Each I

For intCounter = 0 to str1.Length - 1

似乎工作谢谢大家的帮助

1 个答案:

答案 0 :(得分:0)

    Dim Cnt As Integer = 0
    Dim Total As Integer = 0
    Dim Max As Integer = 0
    Dim Min As Integer = -1

    For Each vChr As Char In "Test0123" 'Loop over each character one at a time
        If IsNumeric(vChr) Then
            Cnt += 1 'Check to see if character is numeric
            Total += Val(vChr) 'Add number to total
            If Val(vChr) > Max Then Max = Val(vChr) 'If number is higher than max set it as max
            If Min = -1 Then 'If no min is set
                Min = Val(vChr) 'set min
            Else
                If Val(vChr) < Min Then Min = Val(vChr) 'set min if number is lower
            End If
        End If
    Next

    MsgBox("Number Count: " & Cnt)
    MsgBox("Average: " & Total / Cnt) 'get average
    MsgBox("Max: " & Max)
    MsgBox("Min: " & Min)

希望这会有所帮助,请阅读说明并尝试查看其工作原理。