[comp.lang.pascal] Subs. Char. in a String

ZCCBJSB%EB0UB011.BITNET@cunyvm.cuny.edu (Josep Sau B.) (04/23/91)

Robert Oliver Jr. <robby@nuchat.sccsi.com> asked:

> dose any body have some code that can detect a space in a
> string[40] and  it with a -, but if there is not a space
> then dont do anything ?

This is a one char in / one char out substitution in
any string type:

FUNCTION SubstituteChar (s :STRING; InCh, OutCh :CHAR) :STRING;
  VAR i : BYTE;
  BEGIN
    FOR i := 1 TO LENGTH(s) DO IF s(.i.)=InCh THEN s(.i.) := OutCh;
    SubstituteChar := s;
  END;

A more generic solution would be a subprogram like
the PL/I or REXX function TRANSLATE:

FUNCTION Translate (s, target, origin: STRING);
  VAR i, j : BYTE;
  BEGIN
    FOR i := 1 TO LENGTH(s) DO BEGIN
      j := pos(si!,origin);
      IF j > 0 THEN si! := targetj!;
    END;
    Translate := s;
  END;

This subprogram translates any character of S,
found in Origin to the character with the same
index in Target.
Target and Origin should be of the same length.

For example, Translate('abcdefghi','abc','def') = 'abcabcghi';

-- Josep Sau

'...and he amazed with the marvels that are in the world,
    and he asked about things he did not understand,
    and he taught about things he knew.'
 Raimundus Lulius - _Llibre_de_Meravelles_