2017-04-10 82 views
-6

我是新来的编程世界,我被困在下面的问题,请你能帮助我Visual Basic编程

编写Visual Basic.net函数来计算在输入所有数字的总和领域。例如,如果输入的字符串是:“ICT2611”,那么包含在该字符串中的数字是:2,6,1,1,因此它们的和为2 + 6 + 1 + 1 = 10

+0

Visual Basic和VBA实际上是两回事。为您更新了标签。请记住它将来。另外,请花些时间阅读[帮助页面](http://stackoverflow.com/help),特别是名为[“我可以询问什么主题?”]的章节(http://stackoverflow.com/help /主题)和[“我应该避免问什么类型的问题?”](http://stackoverflow.com/help/dont-ask)。和[阅读关于如何提出好问题](http://stackoverflow.com/help/how-to-ask)并学习如何创建[最小,完整和可验证示例](http://stackoverflow.com /帮助/ MCVE)。 –

+3

*“我是新来的X”*!=无法自行尝试任何事情。 – Filburt

+1

请编辑您的问题并使用代码演示您尝试过的方式以及您遇到问题的位置。 – lukkea

回答

0

下面的代码可以解决你的问题,它使用Regex在提供的字符串中查找表达式(数字1-9)中的任何匹配项,然后在它们进行迭代时对它们进行迭代。

Public Function SumOfString(str As String) As Integer 
    Dim total As Integer = 0 
    For Each i As Match In Regex.Matches(str, "[1-9]") 
     total += i.Value 
    Next 
    Return total 
End Function 

或者同样的事情可以这样来实现,这只是通过串中的每个字符迭代,然后检查,看它是否是一个数字。如果它是一个数字,那么它会计算出来。

Public Function SumOfString(str As String) As Integer 
    Dim total As Integer = 0 
    For Each i As Char In str 
     If Char.IsDigit(i) Then total += Integer.Parse(i) 
    Next 
    Return total 
End Function