2017-04-10 94 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