Improved Mid$ Statement

During the course of my work, I often write complex string parsing and manipulation algorithms. The last thing I want, is to have to add more checks to make sure that my string positions are not negative.

I can avoid the hassle by using the following function when I need to use Mid. It wraps around native Visual Basic functionality and handles this common error case.


public Function FlexiMid(From as string, Start as Long, _
       optional Length as Long = -1) as string

    If Start < 1 then Start = 1
    FlexiMid = IIf(Length = -1, mid$(From, Start), _
               mid$(From, Start, Length))

End Function

Once you've pasted this function into your program (I recommend a module, so that you can access it from anywhere), you can use it just as you would Mid. In fact, once I wrote this, I ran a search and replace on my project to start using it.



Comments

  • MID$

    Posted by Legacy on 08/19/2002 12:00am

    Originally posted by: Arjen Stins


    public Function FlexiMid(From as string, Start as Long, optional Length as Long = -1) as string
    If Start < 1 then Start = 1
    If Length < 1 Then
    FlexiMid = mid$(From, Start)
    Else
    FlexiMid = mid$(From, Start, Length)
    End if
    End Function

    Don't use iif with functions in true and false part.
    They are both evaluated. In the original FlexiMid, all mid$ are processed, but only 1 result is returned.

    In this Flexmid only the mid$ that's returned is processed.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds