Here is one more way to do it. It should work fine for ABAP release 702 and above.
- DATA: text TYPE string VALUE 'You need to count # # and #',
- substring TYPE c VALUE '#'.
- DO count( val = text
- sub = substring ) TIMES.
- text = replace( val = text
- sub = substring
- with = substring && sy-index
- occ = sy-index ).
- IF sy-subrc NE 0.
- EXIT.
- ENDIF.
- ENDDO.
- WRITE text.
/.