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

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

  • Do you know where your data is? Consumer cloud-based file sharing services store your sensitive company data on servers outside of your control, outside of your policy and regulatory guidelines – maybe even outside your country – and not managed by you. The potential for data leakage, security breaches, and harm to your business is enormous. Download this white paper to learn about file sync and share alternatives that allow you to manage and protect your sensitive data while integrating and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds