How to extract all digits from a string in Pascal

1 Answer

0 votes
program ExtractDigits;

{$mode objfpc}{$H+}{$H-}

{
    This program demonstrates how to scan a string and collect
    only the digit characters ('0'..'9') into a new string.

    It uses:
      - A dedicated function for clarity
      - Built‑in character classification (using standard operators)
      - A simple and efficient linear scan
}

{
    ExtractDigits
    -------------
    Walks through the input string and appends every digit
    to a result string.

    Parameters:
        S : the input string to examine

    Returns:
        A string containing only the digit characters found in S.
}
function ExtractDigits(const S: string): string;
var
  i: Integer;
  resultDigits: string;
begin
  resultDigits := '';

  { Iterate through each character in the string }
  for i := 1 to Length(S) do
  begin
    { Check whether the character is a digit using Pascal's built‑in range test }
    if (S[i] in ['0'..'9']) then
      resultDigits := resultDigits + S[i];
  end;

  { Return the collected digits }
  Result := resultDigits;
end;

var
  str: string;
  digits: string;

begin
  { Example input string }
  str := '5 ruby8go 9001 c c++ 17python';

  { Extract all digits }
  digits := ExtractDigits(str);

  { Display results }
  WriteLn('Original: ', str);
  WriteLn('Digits:   ', digits);
end.


{
run:

Original: 5 ruby8go 9001 c c++ 17python
Digits:   58900117

}

 



answered Sep 16 by avibootz
...