Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

To find the length of a string... 1

Status
Not open for further replies.

ashykhanna

Programmer
May 27, 2002
14
IN
hello,
can anyone let me know how to find the length of a given string using cobol.
suppose,

10 ws-data pic x(64)

i move some string to this variable.i would like to find the length of the string moved to ws-data.
its very urgent.
thank you,
Ashok..
 
This works...
[tt]
WORKING-STORAGE SECTION.

01 WORK-FIELDS.
03 WS-LONG-STRING PIC X(1000).
03 WS-BLANK-STRING PIC X(100) VALUE SPACES.
03 WS-COUNTER PIC 9(04).

PROCEDURE DIVISION.

MOVE "SAMPLE DATA" TO WS-LONG-STRING.

INSPECT WS-LONG-STRING TALLYING WS-COUNTER
FOR CHARACTERS BEFORE INITIAL WS-BLANK-STRING.

[/tt]
 
Ygor,

Your code will not find the 'correct' end of a string if it is longer than 900 characters. Also, you forgot to initialize the TALLYING data item.

A slight modification, and then it will work.
Code:
WORKING-STORAGE SECTION.

01  WORK-FIELDS.
    03  WS-LONG-STRING.         
        05 WS-LONG-STRING-TO-TEST     PIC X(1000).
        05 WS-BLANK-STRING            PIC X(100)
                                      VALUE SPACES. 
    03  WS-COUNTER                    PIC 9(04).

PROCEDURE DIVISION.

    MOVE ALL "SAMPLE    " TO WS-LONG-STRING-TO-TEST.
    MOVE 0 TO WS-COUNTER.
    INSPECT WS-LONG-STRING TALLYING WS-COUNTER
      FOR CHARACTERS BEFORE INITIAL WS-BLANK-STRING.
    DISPLAY WS-COUNTER
This should display 996.

WS-BLANK-STRING should be as long as needed to define correctly the 'end' of a string. It may need to be as long as the maximum length of the string being tested if embedded spaces are not constrained.

Frederico, this may be faster than the binary search.

Tom Morrison
 
On some platforms, a 1-byte compare is very fast, much faster than a variable-length compare, so the simple
Code:
  PERFORM VARYING var FROM length_of_string BY -1 UNTIL var < 1 OR string(var:1) NOT = SPACE
    CONTINUE
  END-PERFORM
should be fastest except for a very long string, and it is the simplest, most straight forward, and, to my mind, clearest implementation. This could be supplemented by an initial compare to SPACE to eliminate the < 1 inside the loop.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top