How to remove the leading and trailing commas from a string in Pascal

1 Answer

0 votes
program RemoveLeadingTrailingCommas;

function TrimCommas(const S: string): string;
var
  StartPos, EndPos: Integer;
begin
  StartPos := 1;
  EndPos := Length(S);

  // Find the first non-comma character
  while (StartPos <= EndPos) and (S[StartPos] = ',') do
    Inc(StartPos);

  // Find the last non-comma character
  while (EndPos >= StartPos) and (S[EndPos] = ',') do
    Dec(EndPos);

  // Extract the substring without leading and trailing commas
  TrimCommas := Copy(S, StartPos, EndPos - StartPos + 1);
end;

var
  OriginalStr, TrimmedStr: string;
begin
  OriginalStr := ',,,,Pascal,,,';
  
  TrimmedStr := TrimCommas(OriginalStr);
  
  WriteLn('Original: "', OriginalStr, '"');
  WriteLn('Trimmed: "', TrimmedStr, '"');
end.



(*
run:

Original: ",,,,Pascal,,,"
Trimmed: "Pascal"

*)



 



answered Mar 6, 2025 by avibootz

Related questions

...