How to reverse an array of characters without affecting the special characters in Pascal

1 Answer

0 votes
program ReverseVectorChars;

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

// Define a dynamic character array type (acts as a vector of characters)
type
  TCharVector = array of Char;

{ 
  Checks if a character is alphabetic 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 character vector in-place,
  leaving special characters, spaces, and digits in their original positions.
}
procedure ReverseOnlyLetters(var Vec: TCharVector);
var
  Left, Right: Integer;
  Temp: Char;
begin
  if Length(Vec) = 0 then
    Exit; // Guard against empty vectors

  Left := Low(Vec);   // 0-indexed for dynamic arrays
  Right := High(Vec);

  // 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(Vec[Left]) do
      Inc(Left);

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

    // Swap the valid letters found at both pointers
    if Left < Right then
    begin
      Temp := Vec[Left];
      Vec[Left] := Vec[Right];
      Vec[Right] := Temp;
      
      Inc(Left);
      Dec(Right);
    end;
  end;
end;

{ Helper function to convert a standard string into a TCharVector }
function StringToCharVector(const S: string): TCharVector;
var
  I: Integer;
begin
  SetLength(Result, Length(S));
  for I := 1 to Length(S) do
    Result[I - 1] := S[I]; // Free Pascal strings are 1-indexed, dynamic arrays are 0-indexed
end;

{ Helper function to convert a TCharVector back into a standard string }
function CharVectorToString(const Vec: TCharVector): string;
var
  I: Integer;
begin
  SetLength(Result, Length(Vec));
  for I := 0 to High(Vec) do
    Result[I + 1] := Vec[I];
end;

var
  InputStr: string;
  CharVec: TCharVector;
begin
  // Input string specified
  InputStr := 'a#b$%c&*(def!';
  Writeln('Original: ', InputStr);

  // Convert the string into a vector of characters (array of Char)
  CharVec := StringToCharVector(InputStr);

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

  // Convert back to string for neat display output
  Writeln('Reversed: ', CharVectorToString(CharVec));

end.


(*
run:

Original: a#b$%c&*(def!
Reversed: f#e$%d&*(cba!

*)

 



answered 2 days ago by avibootz

Related questions

...