This post will demonstrate a function to trim a string. By trim, I mean to remove all trailing spaces and stop at the first non space character.
The Function
Here is the function, which I’ve added to my Action! library. A new version will be released soon that will include recent additions and many fixes. It’s pretty well documented, but here is a short summary.
The procedure is called by passing a reference to a character array in (the string you want to trim). This procedure will modify it directly, so it can not be a static string and must be a variable. The procedure will start by setting a counter to the length of the incoming string. It will move from the end to the beginning by decreasing this counter. It examines the character at the counters position in the string. If it’s a space, it sets the the new string length to the counter position minus one (to eliminate the space). If it’s not a space, the procedure exits having found a termination point. Each iteration through the loop, the counter is decremented by one to move one character left.
; -------------------------------------- ; Proc..: StrTrim(CHAR POINTER ps) ; Param.: pS=Pointer to string to trim ; Desc : Trims space from string end ; -------------------------------------- PROC StrTrim(CHAR POINTER pS) BYTE bL,bC ; Set counter to end of string bL=pS(Ø) ; Loop from string end to start while bL>=1 DO ; If char is space, set len to curr-1 if pS(bL)=32 then bC=bL-1 else ; Char is not space, exit loop exit fi ; Decrease counter bL==-1 OD ; Set string pointer length to new value pS(Ø)=bC RETURN
Sample Usage
Here is a sample program demonstrating its use. Note that the function has been incorporated into the file LIBSTR.ACT so you don’t see it in this source:
; Include library file that has StrTrim() in it. INCLUDE "D3:LIBSTR.ACT" MODULE PROC Main() ; Declare character array of 20 in length CHAR ARRAY cA(20) ; Copy some content in the char array defining all 20 chars SCopy(cA,"12345 abc ! ") ; Print it to show a valid padded definition PrintF("B4 : [%S]%E",cA) ; Call the trim function passing the char array pointer StrTrim(cA) ; Print it again to show its been trimmed PrintF("Aft: [%S]%E",cA) RETURN