A REAL VB .net Equivalent To The C/C++ atoi()

For awhile now I’ve used the following code that I got from here to translate text into integers without too much fuss in Visual BASIC:

Public Function ToInteger(ByVal s As String) As Integer
    Dim i as Integer
    Integer.TryParse(s, i)
    Return i
End Function

It’s pretty straightforward: The TryParse() tests the string and places the numeric value into ‘i’ if valid, else 0. It doesn’t exception like CInt() would, which makes a difference when processing large amounts of data – exceptions take a fair bit of time to process within try/catch blocks (and one would argue even more outside!)

There’s a catch, though: TryParse() is not exactly like C’s atoi(), and the difference is quite irritating since I come from that background. Specifically, if there is any trailing non-numeric data in the string, it fails. And since I like to use this to convert combo or listbox entries, you can imagine how annoying it is to fail on a string like “212 (Temperature of boiling water”)” or similar: Whereas our ToInteger() function would return 0, atoi() would return 212, stopping after the number.

So, time to get a bit more complicated – meet ToInteger() Mark II. It’s in VB, but it shouldn’t be too hard to convert to C#:

 Public Function ToInteger(ByVal s As String, Optional ByVal result As Integer = 0) As Integer
        Dim i As Integer = 0
        Dim valid As Boolean = False
        Const Asc_0 As Integer = Asc("0"c)
        For Each c As Char In s.TrimStart
            If (c < "0"c OrElse c > "9"c) Then
                Exit For
            End If
            valid = True
            i = i * 10 + (Asc(c) - Asc_0)
        Next
        If (valid) Then
            Return i
        End If
        Return result
    End Function

This version takes in the string, processing digits until they end, then stops with that value, so text following it is ignored. As well, you can (optionally) specify a default value other than 0, useful if you need to know if the input is invalid (no digits input at the string’s start). And despite being longer, it actually timed 25% FASTER than the previous routine – go figure.

Enjoy!

SOME ITEMS YOU MIGHT ENJOY
ASP.NET and VB.NET Web Programming
$3.99
End Date: Sunday Mar-26-2017 10:30:26 PDT
Buy It Now for only: $3.99
Buy It Now | Add to watch list
Programming With Microsoft Visual Basic.net
$3.65
End Date: Friday Mar-24-2017 23:05:14 PDT
Buy It Now for only: $3.65
Buy It Now | Add to watch list
Learn VB .NET Through Game Programming
$6.32
End Date: Friday Mar-24-2017 8:31:26 PDT
Buy It Now for only: $6.32
Buy It Now | Add to watch list


Leave a Reply

Your email address will not be published. Required fields are marked *