I'm just learning COBOL; I'm writing a program that simply echos back user input. I have defined a variable as:
User-Input PIC X(30).
Later when I ACCEPT User-Input, then DISPLAY User-Input " plus some extra text", it has a bunch of spaces to fill the 30 characters. Is there a standard way (like Ruby's str.strip!) to remove the extra spaces?
PROCEDURE DIVISION. MOVE '123456 ' TO VARIN UNSTRING VARIN DELIMITED BY ' ' INTO VARSWAP INSPECT VARSWAP REPLACING LEADING SPACE BY '0' MOVE VARSWAP TO VARIN DISPLAY VARIN STOP RUN.
PROCEDURE DIVISION. PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I > FUNCTION LENGTH(WS-STR) IF WS-STR(WS-I:1) = '*' THEN CONTINUE ELSE MOVE WS-STR(WS-I:1) TO WS-LETTER(WS-J) ADD 1 TO WS-J ADD 1 TO WS-CNT END-IF END-PERFORM DISPLAY WS-CHAR STOP RUN.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
One would hope for a more elegant way of simply trimming text strings but this is pretty much the standard solution... The trimming part is done in the SHOW-TEXT paragraph.
*************************************
* TRIM A STRING... THE HARD WAY...
*************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTX.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 USER-INPUT PIC X(30).
01 I PIC S9(4) BINARY.
PROCEDURE DIVISION.
MOVE SPACES TO USER-INPUT
PERFORM SHOW-TEXT
MOVE ' A B C' TO USER-INPUT
PERFORM SHOW-TEXT
MOVE 'USE ALL 30 CHARACTERS -------X' TO USER-INPUT
PERFORM SHOW-TEXT
GOBACK
.
SHOW-TEXT.
PERFORM VARYING I FROM LENGTH OF USER-INPUT BY -1
UNTIL I LESS THAN 1 OR USER-INPUT(I:1) NOT = ' '
END-PERFORM
IF I > ZERO
DISPLAY USER-INPUT(1:I) '@ OTHER STUFF'
ELSE
DISPLAY '@ OTHER STUFF'
END-IF
.
Produces the following output:
@ OTHER STUFF
A B C@ OTHER STUFF
USE ALL 30 CHARACTERS -------X@ OTHER STUFF
Note that the PERFORM VARYING statement relies on the left to right evaluation of the UNTIL clause to avoid out-of-bounds subscripting on USER-INPUT in the case where it contains only blank spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With