Search code examples
rpglerpg

How to count the number of identical letters in a string in RPG


I would like to count the number of 'i' in the name 'olivia' but I have the impression that my condition is not valid?

How to do charAt in RPG 4 please?

FOR i = 1 to %len(name);
  IF %check(name : letter) = 0;
    count += 1;

  ENDIF;

ENDFOR;

Here is the complete code:

**free

dcl-s name        varchar(50);
dcl-s letter      char(1);
dcl-s count       packed(2:0);
dcl-s i           packed(3:0);
dcl-s waitInput   char(1);
dcl-s message     varchar(50);

name = 'olivia';
letter = 'i';
count = 0;

FOR i = 1 to %len(name);
  IF %check(name : letter) = 0;
    count += 1;

  ENDIF;

ENDFOR;

message = 'The name ' + %char(name) + ' has ' + %char(count) + 'time(s) the letter ' + (letter) ;
dsply message '' waitInput;

*INLR = *on;

Solution

  • IF %check(name : letter) = 0;
    

    =>

     IF %subst(name :i:1) = letter;