Post Reply 
Bug or Not? Taking STRING of a string whilst making leading zeros
01-31-2018, 03:05 AM
Post: #14
RE: Bug or Not? Taking STRING of a string whilst making leading zeros
Some interesting solutions I might not have thought of myself.

Here are two functions I've been using to left- or right-justify a string. Arguments are a string to be processed, the desired length of the resulting string, and the filler character, could be anything but probably 0 or space most common. T

Code:
StrLJust(str,len,spacer)
BEGIN
  LOCAL j,strdim:=DIM(str);
  IF len>strdim THEN
    FOR j FROM strdim TO len-1 DO
      str:=str+spacer;
    END;
  END;
  RETURN(str);
END;

StrRJust(str,len,spacer)
BEGIN
  LOCAL j,strdim:=DIM(str);
  IF len>strdim THEN
    FOR j FROM strdim TO len-1 DO
      str:=spacer+str;
    END;
  END;
  RETURN(str);
END;

But looking at the ITERATE command, this can definitely be made more compact:
Code:
StrLJust(str,len,spacer)
BEGIN
  RETURN(IFTE(DIM(str)<len,str+ITERATE(str+spacer,str,spacer,len-DIM(str)-1),str);
END;

StrLRJust(str,len,spacer)
BEGIN
  RETURN(IFTE(DIM(str)<len,ITERATE(str+spacer,str,spacer,len-DIM(str)-1)+str,str);
END;

Thanks Carlos! Have you made benchmark comparisons between FOR loop and ITERATE? Would be curious if one is faster than the other.
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Bug or Not? Taking STRING of a string whilst making leading zeros - Jacob Wall - 01-31-2018 03:05 AM



User(s) browsing this thread: 1 Guest(s)