Monday, September 1, 2008

Use the LotusScript Split function to write simpler code

PROGRAMMING POWER

By Mick Moignard

How many times have you declared an array in LotusScript and then tediously initialised the elements in it one-by-one? If you're like me, you've probably initialized with code like:

dim Things(17) as String
Thing(0) = "First"
Thing(1) = "Second"

right down to

Thing(17) = "Seventeenth"

And, if you're like me, you were probably getting quietly bored while you are typing it all, as well as being conscious that these 19 lines of code at the start of the function always mean that you have to scroll down to see the code.

I've done this more than a few times. I've often looked for a better way of doing such a thing -- add to that the fact that as a programmer, I'm a bit lazy, so I'll happily spend a little time looking for something cool that will mean I have to type (and maintain) less code.

This approach is relatively hard to maintain, especially when someone wants a new value "Five and a Half", meaning that not only do you extend the Dim statement, but you then have to renumber all the element references after the change.

The LotusScript Split function, new in Release 6 (yes, that long ago) comes to the rescue here. Designer Help says that Split "Returns an Array of Strings that are the substrings of the specified String", and is used like this:

Split (expression [, delimiter [, count [, compMethod ]]])

where Expression is the string to split up, using the optional Delimiter as the delimiter to split at. The count parameter enables you to have split return the first n split-off values, rather than the whole list, and the last one specifies various ways to search for the delimiter -- options around the case and pitch of the delimiter. The first two, are the important ones.

Using Split on my original example, all I then needed to code would be:

dim Things as Variant
Things = Split("First, Second, Third...... , Seventeenth",",")

This certainly saved some time, and when I have to make the change, all I change is:

dim Things as Variant
Things = Split("First, Second, Third..., Five and a Half, ... , Seventeenth",",")

By now you've probably realised that Split is not a long way away from the functionality offered by @Explode in formula language. You'll also note that, in the example, Things has become a Variant, too. We'll discuss that a bit later on, when we've looked at some more useful things to do with Split than just using it to initialise arrays. Like @Explode, It's a great tool in parsing strings, given a little bit of forethought.

Here's a simple example. I wanted to generate a filename with the date as part of the name. I'd get the date and time with @Now, but of course here in the UK, dates derived from @Now have "/" in them as the data separator, and ":" as the time separator. Neither of those characters are allowed in file names.