Saturday, December 16, 2023

Formatting Strings

In the category of building on the shoulders of giants, I adapted the idea Eric Selje presented in String.Format for Visual FoxPro and added support for string interpolation. This makes it much easier to code and read statements that combine expressions into a string.

For example, rather than writing (and later trying to understand):

lcMessage = 'The balance for ' + lcUser + ' on ' + transform(datetime()) + ;
    ' is ' + transform(lnBalance)
use this:
lcMessage = Format('The balance for {lcUser} on {datetime()} is {lnBalance}')

You can get Format.prg from my GitHub repository.

3 comments:

wOOdy said...

Wow, my initial idea came a long way :) Congrats to this clever solution!

BTW, as they say "there are always three ways to skin a... errr: code a function in FoxPro", here's a IMHO slightly shorter code for
lcUser = alltrim(substr(sys(0), at('#', sys(0)) + 1))

lcUser = GetWordNum(sys(0),2,'#')

Greetings from good ol' Bavaria!
wOOdy

Walter Meester said...

I'd use TEXTMERGE() for such cases. I have not used the format function, I can imagine there is more cleverness in there, however for cases above TEXTMERGE() is just working fine for me.

Doug Hennig said...

Format goes beyond TEXTMERGE: it can format numeric and date values and insert carriage returns and linefeeds easily. See the Git repository for details.