I'm always interested in finding the best way to determine the length of a string and was eager to read a previous Q&A on that topic. I have a question about this part of that answer:
So, how do you count the characters that count? One way in COBOL is to make sure that your string ends in nulls and then use INSPECT:
Move All X'00' To str
Move "Hello! how r u" To str(1:14)
INSPECT str Tallying ctr For All Characters Before X'00'
Display 'Variable str has ' ctr ' characters in it'
When you do this, Move "Hello! how r u" To str(1:14), don't you already know the length of the string since you're moving 1:14? What more does INSPECT and tally tell you?
I usually decrement a counter and count down from the end of a string until I find a non-space character. It just seems like COBOL should have a function to do this. I have to do this quite often using COBOL to populate VARCHAR fields for DB2.
QUESTION POSED ON: 24 MAR 2005
QUESTION ANSWERED BY: Tom Ross
In my example, I wanted to use a null-terminated check, and, in order to set up the data item correctly, I had to limit the receiver to 14 characters or the rest of the receiver would be filled with spaces, not nulls. Move "Hello! how r u" To str would move the string then blank out the rest of str. The MOVE was to set up the problem, not part of the solution.
If your fields are always blank filled, then you can count down from the end and use COBOL functions to do something like that as well. There could never be a length function that would work for all users, because many users have null-terminated strings, others have blanks, others have commas to delimit the string. That is why COBOL has DELIMITED BY. Another way to solve the problem and move data at the same time (the DELIMITED BY field below is 2 blanks, x'4040'):
UNSTRING input-field DELIMITED BY ' ' INTO varchar-chars COUNT IN varchar-length
|
 |
|