Menu

Replacing trailing spaces by NUL

2022-10-15
2022-10-16
  • serge lacombe

    serge lacombe - 2022-10-15

    Hi,

    What is the best way (more efficient) to replace trailing spaces in a string by x"00".

    Thanks.

     
    • Vincent (Bryan) Coen

      On 15/10/2022 14:37, serge lacombe wrote:

      Hi,

      What is the best way (more efficient) to replace trailing spaces in a
      string by x"00".

      W-S
      A1   pic 9(4).   *> or larger if needed.

      Proc.

      move FUNCTION STORE-CHAR-LENGTH (string-field) to A1.

      add 1 to A1.
      move low-value to string-field (A1:1).

       
  • Simon Sobisch

    Simon Sobisch - 2022-10-15

    Depends what the string is, if it is a variable and you want it all low value, then INSPECT REPLACING TRAILING SPACES BY LOW-VALUES.
    If you want to pass it to C and want it null-terminated only, I'd search for the last non-space, non-null place and and replace only that.
    If you want a null-terminated string from a literal: z'literal here'.

     
  • serge lacombe

    serge lacombe - 2022-10-15

    Thanks!

     
  • Simon Sobisch

    Simon Sobisch - 2022-10-16

    The solution from @vcoen is the most efficient way, and you can have both "all trailing spaces" and "prepare as C string - with the option to modify everything from C (MOVE LOW-VALUE TO string-field(a:).

    Just two things to watch out:
    * FUNCTION STORED-CHAR-LENGTH is a GnuCOBOL only extension
    * you need to check that the result is not greater than LENGTH OF string-field - but even then you have to take care of the maximum size being not followed by a low-value

    If you only want to pass it to an external code and want to not have that changing the result you can play save and conforming to COBOL2022 standard (only GnuCOBOL implements the first function, I think) with:

               CALL 'somefunc'
                  USING FUNCTION CONCAT (
                            FUNCTION TRIM (string-field, TRAILING),
                            LOW-VALUE )
    

    ... at least this should work, can someone try?

     

Anonymous
Anonymous

Add attachments
Cancel