Archive - Originally posted on "The Horse's Mouth" - 2008-10-31 07:25:26 - Graham Ellis
If you want to format your data neatly in columns, you can use sprintf or printf to do so if you're using a fixed width font. A format of "%20s", for example, calls for a string that's 20 characters long and will be trailing space padded ... except ...that figure "20" is a minimum width, and if your text is longer, the output line will also be longer!
There are two possible solutions you can apply. The first is to use a format of the form "%20.20s" which says "make it 20 wide and TRUNCATE the string to 20 characters if it's longer" ... which might be fine in some circumstances, but eliminate vital data in others. The second solution is to use dynamic formatting. Here's how it works
a) Look through all the data that has to go into a particular field, and note the longest string's length