Visual Basic で、文字列内のすべての数字の合計を取得するにはどうすればよいですか?
- -例えば - -
Dim userWord As String
userWord = Console.ReadLine()
ユーザー入力: 「キツネが 12 の月を飛び越えた」
出力表示: 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
これまでのコードにあるものは次のとおりです。
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 について詳しく説明していただけますか?
何か不足していますか?
あなたは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