在 Visual Basic 中,如何获得字符串中所有数字的总和?
- -例如 - -
Dim userWord As String
userWord = Console.ReadLine()
用户输入:“Fox jumped over the 12 moon”
输出显示:3
jereon 说的:
Dim mytext As String = "123a123"
Dim sum As Integer = 0
For Each ch As Char In mytext
Dim i As Integer
If Integer.TryParse(ch, i) Then
sum += i
End If
Next
Dim mytext As String = "Fox jumped over the 12 moon"
Dim i As Integer = 0
For Each ch As Char In mytext
Dim temp As Integer = 0
If Integer.TryParse(ch, temp) Then
i += temp;
End If
Next
您可以使用 Linq
Dim input As String = "Fox jumped over the 12 moon"
Dim sum As Integer = input.Where(Function(c) [Char].IsDigit(c))
.Sum(Function(x) Integer.Parse(x.ToString()))
这会提取所有数字字符 ( [Char].IsDigit]
),然后将这些字符转换为整数 ( Integer.Parse
),同时对它们求和。
到目前为止,这是我的代码中的内容:
Dim userWord As String
Dim myChars() As Char = userWord.ToCharArray()
Dim i As Integer = 0
For Each ch As Char In myChars
If Char.IsDigit(ch) Then
i += Convert.ToInt32(ch)
End If
Next
Console.WriteLine("Sum of all digits in the String: ")
Console.WriteLine(i)
用户输入:Fox12 输出:99
我希望输出为 3 (1 + 2 = 3)。你能详细说一下1 + 2 = 99吗?
我错过了什么吗?