Search code examples
stringreversetrimcobolinspect

COBOL: How to count all characters after trimming all the spaces before and after Input


STRING FUNCTION TRIMR(EINA01 OF FORMAT1)     
       DELIMITED BY SIZE                     
   INTO WORTTXT1                             
END-STRING.                                  
MOVE FUNCTION REVERSE (WORTTXT1) TO WORTTXT2.
STRING FUNCTION TRIMR(WORTTXT2)              
       DELIMITED BY SIZE                     
   INTO WORTTXT3                             
END-STRING.                                  
INSPECT WORTTXT3 TALLYING LOO FOR CHARACTERS 
                 BEFORE INITIAL SPACES.      


   MOVE EINN01 OF FORMAT1 TO X.              
   MOVE EINN02 OF FORMAT1 TO Y.              
   MOVE EINA01 OF FORMAT1 (X:Y)              
     TO AUSA01 OF FORMAT1.                   

Our problem is that if we exceed the length of the Variable EINA01, which is 50, the program crashes.

Our idea was to trim all the spaces from left and right and count all characters of the input given.

THe problem we face is that we have no way to count all the characters, since we would usually do it with "Inspect count all characters before initial spaces". But if we for example have an input like "Hello World" he would only count everything till the first space after "Hello".


Solution

  • If you want to get the length of a string there a couple of different methods to do this:

    METHOD 1

    a simple loop:

    WS-INPUT-STRING  PIC  X(100) VALUE "12345678901234567890".
    WS-OUTPUT-STRING PIC X(50).
    WS-POS           PIC X(4) COMP.
    
    PERFORM VARYING WS-POS
               FROM 100 BY -1
               UNTIL WS-INPUT-STRING(WS-POS:1)
                     NOT EQUAL SPACE OR
                     WS-POS < 1
    END-PERFORM
    IF WS-POS <= 50
       MOVE WS-INPUT-STRING(1:WS-POS) TO WS-OUTPUT-STRING
    END-IF
    

    METHOD 2

    inspect tallying

    WS-INPUT-STRING  PIC X(100) VALUE "12345678901234567890".
    WS-OUTPUT-STRING PIC X(50).
    WS-BLANK-COUNT   PIC 9(4) COMP.
    WS-IN-MAX        PIC 9(4) COMP VALUE 100.
    
    INSPECT FUNCTION REVERSE (WS-INPUT-STRING)
            TALLYING WS-BLANK-COUNT FOR LEADING SPACES
    IF (WS-IN-MAX - WS-BLANK-COUNT) <= 50
       MOVE WS-INPUT-STRING(1:WS-IN-MAX - WS-BLANK-COUNT)
    END-IF
    

    both of these are viable options. I prefer the loop my self.

    Also remember typically, leading spaces are important, I wouldn't recommend trimming them unless you are 100% sure they are not required.