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'.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
The solution from @vcoenis 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:
Hi,
What is the best way (more efficient) to replace trailing spaces in a string by x"00".
Thanks.
On 15/10/2022 14:37, serge lacombe wrote:
Proc.
move FUNCTION STORE-CHAR-LENGTH (string-field) to A1.
add 1 to A1.
move low-value to string-field (A1:1).
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'.Thanks!
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-LENGTHis 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-valueIf 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:
... at least this should work, can someone try?
I think you can probably find another solution by using the REVERSE and INSPECT functions combined ...
See an example at
https://sourceforge.net/p/gnucobol/discussion/help/thread/b5d4124781/?limit=50#eaad