如何获取字符串中所有数字的总和 - Visual Basic 2010(模块)

时间:2013-07-30 15:16:27

标签: vb.net string

如何在visual basic中获取字符串中所有数字的总和?

---例如---

Dim userWord As String
userWord = Console.ReadLine()

用户输入:“Fox跳过了12月”

输出显示:3

5 个答案:

答案 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)

  1. 使用foreach循环遍历字符串中的字符
  2. 尝试将它们转换为int
  3. 保留一个具有总数的变量,如果是整数
  4. ,则添加

答案 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吗?

我错过了什么吗?