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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:28:10  来源:igfitidea点击:

How to get sum of all the digits in a string - Visual Basic 2010 (Module)

vb.netstring

提问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

  1. loop over your chars in your string with a foreach
  2. TryParse them to an int
  3. Keep a variable that has the total and add if it is an integer
  1. 使用 foreach 循环遍历字符串中的字符
  2. 尝试将它们解析为 int
  3. 保留一个具有总数的变量,如果它是整数,则添加

回答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),同时对它们求和。