Three BASIC subroutines that left-justify, centre or right-justify a line of text held in t$, for screen displays or printouts, with a short demo. Listing A asks for a string of up to 32 characters, then centres it (C), pushes it to the right (R) or to the left (L) under a column ruler. Each routine copies t$ into o$, finds the first non-blank character from the left or the right, and puts the characters back in their new places. With a 64-column system such as Zebra Systems OS64, set max to 64 in line 30, or LPRINT in line 210.
As printed, line 4030 of the left-justify routine uses the variable i before it is set, so L stops with 2 Variable not found; centre and right justify work. Steven Gunhouse’s follow-up letter in the next issue gives a single routine that does all three (Justify It Two).
Retyped by GFC from the I.S.T.U.G. newsletter, with minor revisions to the listings.
Published in Sinc-Link March-April 1990 (Tricks of the Trade).
Source Code
Listing A
10 REM Justify It
20 REM by Mike Felerski
30 LET max=32
40 DIM t$(max)
50 DIM o$(max)
60 DIM r$(32)
70 POKE 23658,8
100 GO SUB 300
110 LET t$=r$
112 PRINT AT 14,5;"(L)eft"
120 PRINT AT 15,5;"(C)enter"
130 PRINT AT 16,5;"(R)ight"
140 INPUT "Choice? ";c$
150 IF c$="L" THEN GO SUB 4000: GO SUB 200: GO TO 110
160 IF c$="C" THEN GO SUB 4100: GO SUB 200: GO TO 110
170 IF c$="R" THEN GO SUB 4200: GO SUB 200: GO TO 110
180 GO TO 140
200 REM Clear and Print
205 PRINT AT 8,0;"54321 98765432100123456789 12345"
210 PRINT AT 10,0;t$: RETURN
300 REM Enter String
310 PRINT AT 20,0;"Enter String";max;" Chars Max"
320 INPUT r$: LET t$=r$: GO SUB 200: RETURN
Listing B
4000 REM Left Justify
4005 LET o$=t$: LET pos=0
4010 IF o$(pos+1)=CHR$ 32 THEN LET pos=pos+1: GO TO 4010
4020 IF pos=0 THEN RETURN
4030 FOR x=pos+1 TO max: LET t$(1)=o$(x): LET i=i+1: NEXT x
4040 FOR x=1 TO max: LET t$(x)=CHR$ 32: NEXT x
4050 RETURN
4100 REM Center Justify
4110 GO SUB 4000: LET o$=t$: LET pos=max
4120 IF o$(pos)<>CHR$ 32 THEN GO TO 4150
4130 LET pos=pos-1: IF pos=0 THEN GO TO 4150
4140 GO TO 4120
4150 LET pos=(INT ((max-pos)/2)+1)
4160 FOR x=1 TO pos-1: LET t$(x)=CHR$ 32: NEXT x
4170 LET i=1
4180 FOR x=pos TO max: LET t$(x)=o$(i): LET i=i+1: NEXT x
4199 RETURN
Listing C
4200 REM Right Justify
4205 LET o$=t$: LET pos=max+1
4220 IF o$(pos-1)<>CHR$ 32 THEN GO TO 4230
4222 LET pos=pos-1
4225 IF pos=0 THEN RETURN
4227 GO TO 4220
4230 LET i=max
4235 FOR x=pos-1 TO 1 STEP -1: LET t$(i)=o$(x): LET i=i-1: NEXT x
4240 FOR x=i TO 1 STEP -1: LET t$(x)=CHR$ 32: NEXT x
4250 RETURNNote: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.
