Count Alphabetical characters using VBScript- 2 Methods
In order to count Alphabetical characters using VBScript in a string, first we need to get the characters from the given string, one char at a time using the mid function of VBScript. Then check if the character is a numeric character. If no numeric character is found using isNumeric function, the given string is an alphabetical string.
Using isNumeric: Count alphabetical characters using VBScript
Example code
Function countAlphaChars()
Dim oStr
Dim oLength
Dim oChar
Dim iCounter
oStr="goo23gle5"
oLength=len(oStr)
oAlphacounter=0
For iCounter=1 to oLength
If not isnumeric (mid(oStr,iCounter,1)) then
oAlphacounter=oAlphacounter+1
End if
Next
print oAlphacounter
countAlphaChars=oAlphacounter
End Function
Using ASCII: Count alphabetical characters using VBScript
To count only the alphabetical characters, we need to iterate over each character in a string, checking if it falls within the alphabetic range (A-Z, a-z).
' Define the string to be analyzed
Dim strText
strText = "Hello, World! 123"
' Initialize the counter
Dim alphaCount
alphaCount = 0
' Loop through each character in the string
For i = 1 To Len(strText)
' Get the ASCII code of the current character
Dim charCode
charCode = Asc(Mid(strText, i, 1))
' Check if the character is alphabetical (A-Z, a-z)
If (charCode >= 65 And charCode <= 90) Or (charCode >= 97 And charCode <= 122) Then
alphaCount = alphaCount + 1
End If
Next
' Display the result
WScript.Echo "Total alphabetical characters: " & alphaCount
Explanation of the Code
- Define the Text String: strText holds the text we want to analyze.
- Initialize a Counter: alphaCount starts at 0 and will be used to count each alphabetic character.
- Loop Through Each Character: For i = 1 To Len(strText) goes through each character in the string.
- Identify Alphabetic Characters: Asc() function returns the ASCII code, and we check if it falls within the ranges for uppercase (65-90) and lowercase (97-122) letters.
- Display the Result: The final count of alphabetic characters is shown using WScript.Echo.