Monday, September 26, 2011

COBOL: Determining length of a string

The below code snippet explains how to find the length of a string.


Assume the field definitions are as follows :                    
                                                                     
    05 WS-STRING    PIC X(100).                                  
    05 WS-COUNT     PIC 9(4).                                      
    05 WS-LENGTH    PIC 9(4).                                      
                                                                   
a. MOVE    0 TO WS-COUNT                                            
b. INSPECT WS-STRING REPLACING ALL LOW-VALUE BY SPACE              
c. INSPECT FUNCTION REVERSE(WS-STRING)                              
          TALLYING WS-COUNT FOR LEADING SPACE                      
d. COMPUTE WS-LENGTH = LENGTH OF WS-STRING - WS-COUNT                 

                                                                     
NOTE:                                                                 
   A. Step a. above is very important, as the inspect function does not initialize the field before Tallying.                      
   B. Step b. above is optional, and may be used only if it is possible that the string contains trailing low-values, instead of spaces.                          

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.