How to reverse a string without affecting special characters in Pascal

1 Answer

0 votes
program ReverseStringLetters;

// Compiler directives: modern Object Pascal mode and dynamic long strings enabled
{$mode objfpc}{$H+}

{ 
  Checks if a character is an ASCII letter using Pascal's efficient 
  set membership operator.
}
function IsAlpha(C: Char): Boolean;
begin
  Result := C in ['a'..'z', 'A'..'Z'];
end;

{ 
  Reverses only the alphabetic characters in a string in-place,
  leaving special characters, digits, and spaces in their original positions.
  
  @param AText Reference to the string to modify in-place.
}
procedure ReverseOnlyLetters(var AText: string);
var
  Left, Right: Integer;
  Temp: Char;
begin
  if Length(AText) <= 1 then
    Exit; // Guard against empty or single-character strings

  Left := 1;                    // Free Pascal strings are 1-indexed by default
  Right := Length(AText);

  // Use a two-pointer approach moving inward from both ends
  while Left < Right do
  begin
    // Advance left pointer until it points to an alphabetic character
    while (Left < Right) and not IsAlpha(AText[Left]) do
      Inc(Left);

    // Move right pointer backward until it points to an alphabetic character
    while (Left < Right) and not IsAlpha(AText[Right]) do
      Dec(Right);

    // Swap the valid letters found at both pointers
    if Left < Right then
    begin
      Temp := AText[Left];
      AText[Left] := AText[Right];
      AText[Right] := Temp;

      Inc(Left);
      Dec(Right);
    end;
  end;
end;

var
  MessageText: string;
begin
  // Input string specified
  MessageText := 'ab*#cde!@$,fg{}';

  Writeln('Original:  ', MessageText);

  // Apply the reversal function in-place
  ReverseOnlyLetters(MessageText);

  Writeln('Reversed:  ', MessageText);
end.


(*
run:

Original:  ab*#cde!@$,fg{}
Reversed:  gf*#edc!@$,ba{}

*)

 



answered 2 days ago by avibootz

Related questions

...