3

在 Visual Basic 中,如何获得字符串中所有数字的总和?

- -例如 - -

Dim userWord As String
userWord = Console.ReadLine()

用户输入:“Fox jumped over the 12 moon”

输出显示:3

4

5 回答 5

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
于 2013-07-30T15:46:40.493 回答
2
  1. 使用 foreach 遍历字符串中的字符
  2. 尝试将它们解析为 int
  3. 保留一个具有总数的变量,如果它是整数则添加
于 2013-07-30T15:22:08.950 回答
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
于 2013-07-30T15:25:46.940 回答
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),同时对它们求和。

于 2013-07-30T15:22:40.887 回答
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吗?

我错过了什么吗?

于 2013-07-30T15:44:10.250 回答