Write a visual basic program to find the sum of digits in a string. How to check a char is Digit or not in visual basic. Convert string in a char array in visual basic.
Find a digit from string in Visual basic is really simple. Here is this example, We will see how to find the sum of digits in a string using visual basic. Let’s see the step to find the sum of a string. Visual basic programs with examples.
Steps to find the sum of a digit from a string in VB.
- Read a string value from user input.
- Convert the string into a char Array.
- Check each element of the array isDigit or char.
- Sum all the digit numbers.
Now Let’s see every step with a visual basic program.
How to read value from console in Visual basic.
Console.ReadLine() is used to read a value from console in visual basic as shows in the below code block. We will read a string from the console and initialize the value to a variable(str).
Console.WriteLine("Enter the string..") 'Read Input from user str = Console.ReadLine()
Convert a string into a char array in visual basic
TocharArray() is used to convert the string into a char array in visual basic. In the below example we have a String(str) and an array(a) of char type.
'Convert the string into Char array Dim a() As Char = str.ToCharArray()
Check whether a char is a digit or not in visual basic
Char.IsDigit(ch) is used to check a char is a digit or not in the visual basic. IsDigit() method will take a char as arguments and return a boolean value.
Syntax:
Char.IsDigit(ch)
Visual Basic program to find the Sum of digits in a string.
Hope the above steps are clear, Now its really simple to find the sum of digits in a string in Visual basic. Below is the complete visual basic program to find the sum of the digit.
Module Module1 Sub Main() Dim str As String Console.WriteLine("Enter the string..") 'Read Input from user str = Console.ReadLine() 'Convert the string into Char array Dim array() As Char = str.ToCharArray() Dim sum As Integer = 0 For Each ch As Char In array 'Check digit in the string If Char.IsDigit(ch) Then Dim s As String = ch.ToString() 'Sum of all the numerical values sum += Convert.ToInt64(s) End If Next Console.WriteLine("Sum of all digits in the String: ") Console.WriteLine(sum) Console.ReadLine() End Sub End Module
Output:
Enter the string..
Hello 20 codebun 15
Sum of all digits in the String:
8