如何在visual basic中获取字符串中所有数字的总和?
---例如---
Dim userWord As String
userWord = Console.ReadLine()
用户输入:“Fox跳过了12月”
输出显示:3
答案 0 :(得分:3)
杰里恩说:
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
答案 1 :(得分:2)
答案 2 :(得分:2)
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
答案 3 :(得分:0)
您可以使用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
),同时将它们相加。
答案 4 :(得分:0)
到目前为止,我的代码中包含了以下内容:
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吗?
我错过了什么吗?