System.Length - 获取字符串或数组的长度

时间:2022-09-20 22:26:38

System.Length - 获取字符串或数组的长度
function Length(
  S: String {字符串; 也可以是数组}
): Integer;
--------------------------------------------------------------------------------
举例:
--------------------------------------------------------------------------------
 
//string(在 Delphi 2007 下同 AnsiString)
var
  s: string;
  i: Integer;
begin
  s := 'Delphi';
  i := Length(s);
  ShowMessage(IntToStr(i)); {6}
end;
--------------------------------------------------------------------------------

//ShortString
var
  s: ShortString;
  i: Integer;
begin
  s := 'Delphi';
  i := Length(s);
  ShowMessage(IntToStr(i)); {6}
end;
--------------------------------------------------------------------------------

//string[n]
var
  s: string[10];
  i: Integer;
begin
  s := 'Delphi';
  i := Length(s);
  ShowMessage(IntToStr(i)); {6}
end;
--------------------------------------------------------------------------------

//AnsiString
var
  s: AnsiString;
  i: Integer;
begin
  s := '万一123';
  i := Length(s);
  ShowMessage(IntToStr(i)); {7}
end;
--------------------------------------------------------------------------------

//WideString
var
  s: WideString;
  i: Integer;
begin
  s := '万一123';
  i := Length(s);
  ShowMessage(IntToStr(i)); {5}
end;
--------------------------------------------------------------------------------

//静态数组(Length 是获取数组的元素个数; 获取数组的大小需要用 SizeOf)
var
  i: Integer;
  arr: array[0..10] of Integer;
begin
  i := Length(arr);
  ShowMessage(IntToStr(i)); {11}
end;
--------------------------------------------------------------------------------

//动态数组
var
  i: Integer;
  arr: array of Integer;
begin
  SetLength(arr, 10);
  i := Length(arr);
  ShowMessage(IntToStr(i)); {10}
end;
--------------------------------------------------------------------------------

//多维数组
var
  i: Integer;
  arr: array[0..4, 2..22] of Integer;
begin
  i := Length(arr);
  ShowMessage(IntToStr(i)); {5}
end;