How to reverse only the alphabetic characters in a string, keeping other characters in place with Pascal

1 Answer

0 votes
program ReverseOnlyAlphabeticCharactersProgram;

function IsAlpha(ch: char): boolean;
begin
  ch := UpCase(ch);
  IsAlpha := (ch >= 'A') and (ch <= 'Z');
end;

function reverseOnlyAlphabeticCharacters(s: string): string;
var
  i, j : integer;
  tmp  : char;
begin
  i := 1;
  j := Length(s);

  while i < j do
  begin
    if not IsAlpha(s[i]) then
      Inc(i)
    else if not IsAlpha(s[j]) then
      Dec(j)
    else
    begin
      tmp := s[i];
      s[i] := s[j];
      s[j] := tmp;
      Inc(i);
      Dec(j);
    end;
  end;

  ReverseOnlyLetters := s;
end;

var
  s: string;

begin
  s := 'a1-bC2-dEf3-ghIj';

  writeln(s);
  writeln(reverseOnlyAlphabeticCharacters(s));
end.



(*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*)

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...