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

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

  • Cybercrime is getting big and bigger. 2013 was the year of the Mega Breach with eight top data breaches resulting in the loss of tens of millions of data records. Criminals are always looking for vulnerabilities to exploit. Applications are already becoming a target. Is signing code and apps the answer to protecting our users from malware in applications? Are there any challenges with code signing? In this program we answer those questions and more with two of the industry's leading experts -- Mario de …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds