PASCAL string to array

3.7k Views Asked by At

How can I convert a string of numbers like for example '21354561321535613' into digits and store them in an array?

Each digit should be turned into an integer element in the array, so the string '21354561321535613' should result in:

[2, 1, 3, 5, 4, 5, 6, 1, 3, 2, 1, 5, 3, 5, 6, 1, 3]
4

There are 4 best solutions below

14
On BEST ANSWER

You can easily turn a digit into an integer by subtracting the ordinal value of '0'. Do this in a loop and you have an integer for each digit:

var
  S: string;
  A: array of Integer;
  I, Len: Integer;
begin
  S := '21354561321535613';
  Len := Length(S);

  { Reserve Len Integers. }
  SetLength(A, Len);

  { Convert each digit into an integer: }
  for I := 1 to Len do
    A[I - 1] := Ord(S[I]) - Ord('0'); { [I - 1] because array is zero-based. }
end;
0
On
var
  Str: string;
  Arr: array of Integer;
  i: Integer;
  Len: Integer;
begin
  Str := '21354561321535613';
  Len := Length(Str);
  SetLength(arr, Len);

  for i := 1 to Len do
    Arr[i - 1] := StrToInt(Str[i]);  
end;
0
On

You can use this code to covert String to Array of bytes)

uses crt;
var
        s:string;
        a:array[1..1000] of byte;
        i:byte;
begin
        s:='1234567';
        for i:=1 to length(s) do
                val(s[i],a[i]);
end.
1
On

it sample to convert numbers as string to numbers use the function

 strtoint(number_in_string);

to convert numbers to numbers as string use the function

inttostr(number);