Using 'Replace' Within 'Cond' Statement

I am trying to replace a substring in a string based on certain condtions using COND #. But not sure where to incorporate REPLACE in the syntax.

Normal code:

DATA(v_string) = 'My string &1 &2'.

IF v_string CA '&1'.
  REPLACE '&1' WITH 'sub1' in v_string.
ELSEIF v_string CA '&2'.
  REPLACE '&2' WITH 'sub2' in v_string.
ENDIF.

I am trying to achieve the same using ABAP 7.5 syntax.

v_string = COND #( WHEN v_string CA '&1' THEN REPLACE '&1' WITH 'sub1' in v_string
                   WHEN v_string CA '&2' THEN REPLACE '&2' WITH 'sub2' in v_string ).

What is the correct syntax to get the desired results?

3

1 Answer

As per documentation, the THEN operand must be a a general expression position, which is defined as

Reading position in which (alongside a suitable data object) a constructor expression, a table expression, a calculation expression, a built-in function, a functional method, or a method chaining can also be specified.

That means REPLACE is not available, but you can use built-in string function replace.

v_string = COND #( 
  WHEN contains( val = v_string sub = '&1' ) 
    THEN replace( val = v_string sub = '&1' with = 'sub1' occ = 1 )
  WHEN contains( val = v_string sub = '&2' ) 
    THEN replace( val = v_string sub = '&2' with = 'sub2' occ = 1 )
).
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest