In general your code looks good, here are a few smaller remarks.
Method name:
Capitalize the name of your method and make it more meaningful. Use CountAlphaNumeric
or something similar.
Comments in code:
You can omit the comments in your code. It speaks for itself what the code is doing, certainly because you use clear names for your variables.
IsNumeric() - Char.IsDigit():
In the .NET framework, there's the Char.IsDigit
method, use this one instead:
If Char.IsDigit(c) = True Then numericCount += 1
MsgBox() - MessageBox.Show():
Although MsgBox
is valid, it also comes from the VB era. In the .NET framework there's the MessageBox.Show
method, use that one instead:
MessageBox.Show("Number of alphabets : " & alphaCount)
String.Format():
To insert variables in a string, use the String.Format
instead of just concatenating the values:
Dim result As String = String.Format("Number of alphabets : {0}", alphaCount)
"Expression = True":
You can leave out the = True
part in your if conditions, since the methods return a boolean value.
This is what the code now looks like:
Public Sub CountAlphaNumeric(ByVal input As String)
Dim alphaCount As Integer = 0
Dim numericCount As Integer = 0
For Each c As Char In input
If Char.IsDigit(c) Then numericCount += 1
If Char.IsLetter(c) Then alphaCount += 1
Next
MessageBox.Show(String.Format("Number of alphabets : {0}", alphaCount))
MessageBox.Show(String.Format("Number of numerics : {0}", numericCount)
End Sub
Using LinQ:
Although not always the best option, you can achieve the same result using LinQ, using the Enumerable.Count
method:
Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))
Dim numericCount = input.Count(Function(c) Char.IsDigit(c))
Here's the complete code using LinQ:
Public Sub CountAlphaNumericUsingLinQ(ByVal input As String)
Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))
Dim numericCount = input.Count(Function(c) Char.IsDigit(c))
MessageBox.Show(String.Format("Number of alphabets : {0}", alphaCount))
MessageBox.Show(String.Format("Number of numerics : {0}", numericCount))
End Sub