找出String的长度

时间:2016-08-05 11:28:18

标签: cobol

假设我有一个变量PIC X(20)

该变量包含一些值,例如ABC WXYZ

如何找出字符串的长度,不包括中间的空格?

1 个答案:

答案 0 :(得分:1)

如果你确定不想要介于两者之间的空间,你可以定义test-val并在PERFORM中使用它:

   77  some-len   PIC 9(02). *> make sure to use appropriate length, if "big" use COMP-5
   77  string-ptr PIC 9(02). *> make sure to use appropriate length
   77  some-var   PIC X(20) VALUE '  ABC WXYZ'.
   77  var-len    PIC 9(02) VALUE LENGTH OF some-var.
   01  test-char  PIC X.
       88 no-spaces  values 'A' THROUGH 'Z'
                            'a' THROUGH 'z'
                            '0' THROUGH '9'
                            '-', '.'.  

   PROCEDURE DIVISION.

       MOVE 0 TO some-len
       PERFORM VARYING string-ptr FROM 1 BY 1
               UNTIL   string-ptr > var-len
          MOVE some-var (string-ptr) TO test-char
          IF no-spaces ADD 1 TO some-len END-IF
       END-PERFORM

比尔指出,如果你只想知道"不是空格"那里的角色是一个更快的选项,需要更少的变量(请确保你发表评论,让你和其他人知道它的作用:

  *> set numbers of all non-spaces in some-len
       MOVE 0 TO some-len
       INSPECT some-var TALLYING some-len FOR ALL SPACES
  *> add more counts here if you want to remove more chars like x'0D'/x'0A'/x'00', ...
  *>   INSPECT some-var TALLYING some-len FOR ALL x'00'
  *>   INSPECT some-var TALLYING some-len FOR ALL x'0D'
  *>   INSPECT some-var TALLYING some-len FOR ALL x'0A'
  *> and finally subtract it from the fields length
       SUBTRACT some-len FROM LENGTH OF some-var GIVING some-len
  *>