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)
        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.


Visual Basic.NET: An Introduction to Computer Programming
End Date: Wednesday Jan-10-2018 3:10:18 PST
Buy It Now for only: $8.87
Buy It Now | Add to watch list
CIL Programming : Under the Hood of .NET book by Jason Bock
End Date: Sunday Dec-17-2017 21:55:10 PST
Buy It Now for only: $19.00
Buy It Now | Add to watch list
Pro .NET 2.0 Graphics Programming Paperback Computer Reference Eric White CHOP
$6.23 (0 Bids)
End Date: Sunday Dec-17-2017 5:35:26 PST
Bid now | Add to watch list

Leave a Reply

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