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: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds