Check if string contains Letters?

If you need help with a project or need to know how to do something specific in VB.NET then please ask your questions in here.
Forum rules
Please LOCK your topics once you have found the solution to your question so we know you no longer require help with your query.
5 posts Page 1 of 1
Contributors
User avatar
zachman61
VIP - Donator
VIP - Donator
Posts: 1891
Joined: Wed Dec 16, 2009 9:56 pm

Check if string contains Letters?
zachman61
I'm trying to check if a string contains letters because I need a numerical only string, anyone know how to check if it contains letters?
Nailing my feet to the floor is easier than using my own muscles to balance, but you don't see me doing that :)
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Code: Select all
Dim containsLetter As Boolean
        For i = 0 To s.Length - 1
            If Asc(s.Substring(i, 1)) < 48 Or Asc(s.Substring(i, 1)) > 57 Then containsLetter = True
        Next
        If containsLetter Then MessageBox.Show("The string must contain numbers only!")
You can replace s by the name of your string, and the messagebox is optionnal.

This uses ASCII character codes to determine whether or not the String contains something other than numbers (anything not between 48 and 57, basically).
User avatar
Cheatmasterbw
Coding God
Coding God
Posts: 1506
Joined: Fri Jan 01, 2010 2:30 pm

you can also use the isNumeric function:
Code: Select all
if isNumeric(StringVariable) then
...
end if
http://www.megaapps.tk/
User avatar
Shim
VIP - Donator
VIP - Donator
Posts: 882
Joined: Wed Dec 14, 2011 5:02 am

Re: Check if string contains Letters?
Shim
function
Code: Select all
Function CheckForAlphaCharacters(ByVal StringToCheck As String)


    For i = 0 To StringToCheck.Length - 1
        If Char.IsLetter(StringToCheck.Chars(i)) Then
            Return True
        End If
    Next

    Return False

End Function
usage
Code: Select all
 Dim Mystring As String = "abc123"
    If CheckForAlphaCharacters(Mystring) Then
        'do stuff here if it contains letters
    Else
        'do stuff here if it doesn't contain letters
    End If
##credits stackoverflow
Find my programs on Softpedia
User avatar
zachman61
VIP - Donator
VIP - Donator
Posts: 1891
Joined: Wed Dec 16, 2009 9:56 pm

Thanks, I spent like 30-40 minutes googling but stack overflow didn't popup.
Nailing my feet to the floor is easier than using my own muscles to balance, but you don't see me doing that :)
5 posts Page 1 of 1
Return to “Coding Help & Support”