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
Microsoft ASP.NET Programming with Microsoft Visual Basic .NET by Duthie
$3.50
End Date: Saturday Sep-16-2017 17:52:57 PDT
Buy It Now for only: $3.50
Buy It Now | Add to watch list
Pro ASP.NET 2.0 Website Programming Paperback Reference Damon Armstrong CHOP
$5.93 (0 Bids)
End Date: Monday Aug-21-2017 17:18:43 PDT
Bid now | Add to watch list
Programming ASP.NET MVC 4: Developing Real-World Web Applications with ASP.NE…
$12.99
End Date: Friday Sep-15-2017 12:12:56 PDT
Buy It Now for only: $12.99
Buy It Now | Add to watch list


Leave a Reply

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