vb.net 如何获得字符串中所有数字的总和 - Visual Basic 2010(模块)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17950937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get sum of all the digits in a string - Visual Basic 2010 (Module)
提问by Matt
How do I get the sum of all the digits in a string, in visual basic?
如何在visual basic中获取字符串中所有数字的总和?
---For example---
- -例如 - -
Dim userWord As String
userWord = Console.ReadLine()
User Input: "Fox jumped over the 12 moon"
用户输入:“狐狸跳过了十二个月亮”
Output Display: 3
输出显示:3
采纳答案by dbasnett
What jereon said:
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
回答by JMan
- loop over your chars in your string with a foreach
- TryParse them to an int
- Keep a variable that has the total and add if it is an integer
- 使用 foreach 循环遍历字符串中的字符
- 尝试将它们解析为 int
- 保留一个具有总数的变量,如果它是整数,则添加
回答by Krishna
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
回答by Matt
Here is what I have in my code so far:
到目前为止,这是我的代码中的内容:
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)
User Input: Fox12 Output: 99
用户输入:Fox12 输出:99
I want the output to be 3 (1 + 2 = 3). Could you go into detail how 1 + 2 = 99?
我希望输出为 3 (1 + 2 = 3)。你能详细说明1 + 2 = 99吗?
Am I missing something?
我错过了什么吗?
回答by keyboardP
You can use Linq
您可以使用 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()))
This extracts all the chars that are digits ([Char].IsDigit]) and then converts those chars to integers (Integer.Parse) whilst summing them.
这将提取所有数字 ( [Char].IsDigit])字符,然后将这些字符转换为整数 ( Integer.Parse),同时对它们求和。

