Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to clone a string array?

Tags:

arrays

delphi

I have an array declared as:

const A: array[0..3] of ShortString = (
  'Customer',
  'Supplier',
  'Stock',
  'GL'
);

var B: array of ShortString;

I would like to clone the string array A to another array B. Using Move or Copy function doesn't work. Is there a fast and easy way to clone the array without using for loop?

like image 980
Chau Chee Yang Avatar asked Dec 13 '22 00:12

Chau Chee Yang


2 Answers

The problem you face is that your constant A and your variable B are actually of different types. This can be demonstrated most easily by showing how you would declare a const and a var of the same type in a fashion equivalent to what you show in your question:

type
  TSA = array[0..3] of ShortString;

const
  A: TSA = (
  'Customer',
  'Supplier',
  'Stock',
  'GL');

var B: TSA;

With these declarations you could then simply write:

B := A;

But when A is a dimensioned array and B is a dynamic array, this isn't possible and your only option is to SetLength(B) as required and copy the elements one-by-one.

Although the const and the var types may look like they are the same - or compatible types - they are not, and this then is no different from trying to assign an Integer constant to a String variable... even though you know the simple conversion required to achieve it, the compiler cannot presume to guess that you intended this, so you have to be explicit and provide the conversion code yourself.

like image 70
Deltics Avatar answered Dec 27 '22 02:12

Deltics


Something like:

SetLength(B, Length(A));
for i := Low(A) to High(A) do
  B[i] := A[i];

Or in a more generic way:

type
  TStringArray = array of ShortString;

procedure CloneArray(const source: array of ShortString; var dest: TStringArray);
var
  i: integer;
begin
  SetLength(dest, Length(source));
  for i := Low(source) to High(source) do
    dest[i] := source[i];
end;

In the latter case you'll have to redeclare B as B: TStringArray.

like image 23
gabr Avatar answered Dec 27 '22 04:12

gabr