Standard way to remove spaces from input in cobol?

Shawn J. Goff picture Shawn J. Goff · Jan 12, 2010 · Viewed 27.1k times · Source

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?

Answer

NealB picture NealB · Jan 12, 2010

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.