Using negative subscripts

Tuesday 8 December 2009 @ 5:19 pm

If you need to pull a single character out of a character string, or a single item out of an array, you can use a subscript to identify the position you want like this:

{Customer.Customer Name} [3]

This example starts counting from the left to identify the third character or element.  Over the years I have had people tell me you could use a negative number to count from the right, but I had it stuck in my head that that this was not reliable, so I hadn’t done anything with it.  But I recently decided to do some testing and found that it works well, especially when you want the last character in a string or the last element in the array.  To get the last element in a string you would say:

{Customer.Customer Name} [-1]

To get the last element in an array you could say:

NumberVar array MyArray;
MyArray [-1]

There are other methods using Length, Count or Ubound, but I think the negative subscript is as simple as it gets.

(For examples of my most popular formulas, please visit the FORMULAS page on my website.)

Leave a Reply

Recrystallize Pro