Is there an easy way to clone an array of strings?

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 an array of strings A into another array B. Using the Move or Copy function does not work. Is there a quick and easy way to clone an array without using a loop?

+4
source share
2 answers

The problem you are facing is that your constants A and your variable B are of different types. This can be demonstrated most easily by showing how you declare const and var of the same type according 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 ads, you can simply write:

 B := A; 

But when A is a dimensional array and B is a dynamic array, this is not possible, and your only option is SetLength (B) as needed and copy the elements one at a time.

Although the const and var types may look the same - or compatible types - it is not, and it is no different from trying to assign an Integer constant to a String variable ... although you know the simple conversion needed to achieve it, the compiler cannot assume that you intended to do this, so you have to be explicit and provide the conversion code yourself.

+11
source

Sort of:

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

Or in a more general 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 will have to reuse B as B: TStringArray.

+2
source

Source: https://habr.com/ru/post/1300146/


All Articles