How to remove all non-numeric characters from a string in Pascal

1 Answer

0 votes
program NumericExtractor;

{ Enable Object Pascal mode and extended syntax }
{$mode objfpc}{$H+}

{**
 * Removes all non-numeric characters from a string, returning only digits (0-9).
 * 
 * @param inputStr The source string containing alphanumeric and special characters.
 * @return A new string containing only numeric digits.
 *}
function ExtractNumericOnly(const inputStr: string): string;
var
  i: Integer;
  len: Integer;
  destIndex: Integer;
begin
  len := Length(inputStr);
  
  { Pre-allocate the result string to the maximum possible length 
    to prevent performance penalties from frequent reallocations }
  SetLength(Result, len);
  
  destIndex := 1;
  for i := 1 to len do
  begin
    { Check if the current character is a numeric digit between '0' and '9' }
    if (inputStr[i] >= '0') and (inputStr[i] <= '9') then
    begin
      Result[destIndex] := inputStr[i];
      Inc(destIndex);
    end;
  end;
  
  { Trim the result string down to the exact number of digits found }
  SetLength(Result, destIndex - 1);
end;

{ --- Main Program Demonstration --- }
var
  originalText: string;
  cleanedText: string;
begin
  originalText := '123XYZ +9982-programming 10000000000001language';
  
  cleanedText := ExtractNumericOnly(originalText);

  Writeln('Original: ', originalText);
  Writeln('Cleaned:  ', cleanedText);
end.


(*
run:

Original: 123XYZ +9982-programming 10000000000001language
Cleaned:  123998210000000000001

*)

 



answered 1 day ago by avibootz

Related questions

...