10-07-2015, 10:02 PM (This post was last modified: 10-07-2015 10:09 PM by StephenG1CMZ.)
Post: #13
 StephenG1CMZ Senior Member Posts: 979 Joined: May 2015
RE: Padding a string with spaces
I decided to have a go at this, based on the original syntax.
My changes include:
An input guard against negative/fractional parameters.
The input string is not modified.
In the centre case, a recursive call is used which I think makes the logic clearer, and avoids repeatedly adding spaces one by one. My implementation is probably less efficient, but provides a comparison for the previous logic.
Code:
    EXPORT ZPAD(ST,LNG,DD)  //ST PADDED NOT TRUNC  //LNG IS OUT MINLEN  //DD 1 R −1 L 0 C  BEGIN   LOCAL LL:=ABS(IP(LNG));//INGUARD   LOCAL SPC:=LL-DIM(ST);   LOCAL SPTMP:="";   CASE   IF DD>0 THEN //PAD R    RETURN REPLACE(ST,LL+1,"");//SYN:JOE HORN   END;   IF DD<0 THEN //PAD L     RETURN REPLACE("",SPC+1,ST);   END;    DEFAULT  //PAD C    SPTMP:=ZPAD("",SPC/2,1);//spaces    SPTMP:=SPTMP+ST+SPTMP;    RETURN      IFTE(DIM(SPTMP)<LL,SPTMP+" ",SPTMP);//extra space if odd   END;//CASE  END;  //LAYERED  EXPORT ZPADL(ST,LL)  BEGIN   RETURN ZPAD(ST,LL,−1);  END;    EXPORT ZPADR(ST,LL)  BEGIN   RETURN ZPAD(ST,LL,1);  END;  EXPORT ZPADC(ST,LL)  BEGIN   RETURN ZPAD(ST,LL,0);  END;  EXPORT ZS()  BEGIN    LOCAL ST:="";   LOCAL STIN:="ABC";   //PRINT();   ST:=ZPAD(STIN,9,1);   //PRINT(SIZE(STIN));//unchanged   //PRINT(SIZE(ST));   //PRINT("v"+ST+"V");//v just shows text limits   //WAIT;  END;

Stephen Lewkowicz (G1CMZ)
https://my.numworks.com/python/steveg1cmz
 « Next Oldest | Next Newest »