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

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds