views:

856

answers:

3

How do I check to see if the first character of a string is a number in VB.NET?

I know that the Java way of doing it is:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

But I'm unsure as to how to go about it for VB.NET.

Thanks in advance for any help.

+2  A: 

Here's a scratch program that gives you the answer, essentially the "IsNumeric" function:

Sub Main()
    Dim sValue As String = "1Abc"
    Dim sValueAsArray = sValue.ToCharArray()
    If IsNumeric(sValueAsArray(0)) Then
        Console.WriteLine("First character is numeric")
    Else
        Console.WriteLine("First character is not numeric")
    End If

    Console.ReadLine()
End Sub
Rob
The call to ToCharArray is not necessary. The first character of a string can be referenced by sValue(0).
Chris Dunaway
+5  A: 
Public Function StartsWithDigit(ByVal s As String) As Boolean
        Return (Not String.IsNullOrEmpty(s)) AndAlso Char.IsDigit(s(0))
End Function
Marcus Andrén
A: 

If I were you I will use Dim bIsNumeric = IsNumeric(sValue.Substring(0,1)) and not Dim sValueAsArray = sValue.ToCharArray()

It does not matter what you use both will yield same result but having said thay Dim sValueAsArray = sValue.ToCharArray() will use more memory & Dim bIsNumeric = IsNumeric(sValue.Substring(0,1)) will use less resources. tough both of them are negligible

It is more of suggestion of programing practice than anything else.

Manmeet
Hence me describing it as a scratch program. For an example I'll always forego error-checking and brevity for clarity and ensuring that the intent of the code is shown clearly
Rob