function Copy( S: String; {字符串或动态数组} Index: Integer; {起始位置} Count: Integer {Copy 个数} ): String; {如果参数 S 是动态数组, 这里也应该返回动态数组}
举例:
//从字符串中提取 var ss,s: string; begin ss := 'CodeGear Delphi 2007'; s := Copy(ss,5,4); ShowMessage(s); {Gear} end;
//从静态字符数组中截取字符串 var arr: array[0..25] of Char; s: string; i: Integer; begin {给 arr 装入 26 个大写字母} for i := Low(arr) to High(arr) do arr[i] := Chr(i+65); {提取} s := Copy(arr, 1, 3); ShowMessage(s); {ABC} end;
//从动态数组到动态数组 var arr1,arr2 : array of Integer; i: Integer; begin {设定数组大小} SetLength(arr1, 10); {给数组赋值} for i := Low(arr1) to High(arr1) do arr1[i] := i; {执行 Copy; 注意: 之前没有给 arr2 设置大小, 就是设置了, 在这里也会被重置!} arr2 := Copy(arr1, 0, 3); for i in arr2 do ShowMessage(IntToStr(i)); {会分别显示: 0、1、2} end;
//关于起始位置(仅对字符串, 动态数组另当别论) const ss = 'ABCDEFG'; var s: string; begin s := Copy(ss, 1, 3); ShowMessage(s); {ABC} s := Copy(ss, 0, 3); ShowMessage(s); {ABC} s := Copy(ss, -1, 3); ShowMessage(s); {ABC} s := Copy(ss, -100, 3); ShowMessage(s); {ABC} end;
//关于 Copy 个数 const ss = 'ABCDEFG'; var s: string; begin s := Copy(ss, 2, 6); ShowMessage(s); {BCDEFG} s := Copy(ss, 2, Length(ss)); ShowMessage(s); {BCDEFG} s := Copy(ss, 2, MaxInt); ShowMessage(s); {BCDEFG} end;