简体   繁体   中英

Create a constant array of strings

Delphi中是否有一种方法可以声明一个字符串数组,例如跟随一个字符串?

{'first','second','third'}

try this

Const
Elements =3;
MyArray  : array  [1..Elements] of string = ('element 1','element 2','element 3');

In XE7 you can declare a dynamic array constant like this:

const
  MyArray: TArray<String> = ['First','Second','Third'];

You can use dynamic arrays and try this:

var
  FMyArray: TArray<string>;

function MyArray: TArray<string>;
begin
  if Length(FMyArray) = 0 then
    FMyArray := TArray<string>.Create('One', 'Two', 'Three');
  Result := FMyArray;
end;

While this does do a run-time initialization of a dynamic array on the heap, it also shows that Delphi supports a "pseudo-constructor" on dynamic arrays that allow in-place initialization. (NOTE: the above code isn't thread-safe).

Now all you need to do to find out the length of the array, is use the Length() standard function, or to find the allowed index range, use the Low() and High() standard functions.

If you're using an older version of Delphi, replace the TArray with your own dynamic-array string type such as:

type
  TStringArray = array of string;

You can do this in a indirect way. Create a function like:

procedure assignStringArray(var rasVelden: ArrayOfString; const asVeldenIn: Array Of String);
var
   iLengte, iT1: Integer;
begin
   iLengte := Length(asVeldenIn);
   SetLength(rasVelden, iLengte);
   for iT1 := iLengte-1 downto 0 do
      rasVelden[iT1] := asVeldenIn[iT1];
end;

and call this function like:

assignStringArray(asVelden, ['String1', 'String2', 'String3']);

where:

asVelden: ArrayOfString; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM