delphi xe7 中對數組操作做了很多擴充,比如加入了類似字符串處理的功能。
例如,數組相加
var A: array of integer; B: TBytes = [1,2,3,4]; //Initialization can be done from declaration begin ... A:=[1,2,3]; // assignation using constant array A:=A+[4,5]; // addition - A will become [1,2,3,4,5] ... end;
數組插入
var A: array of integer; begin ... A:=[1,2,3,4]; Insert(5,A,2); // A will become [1,2,5,3,4] ... end;
數組刪除
var A: array of integer; begin ... A:=[1,2,3,4]; Delete(A,1,2); //A will become [1,4] ... end;
數組連接
A := Concat([1,2,3],[4,5,6]); //A will become [1,2,3,4,5,6]
為什么在xe7 中要對數組做這么大的變化呢,當然首先肯定是方便數組編程,其實更深層的原因是因為ansistring 在移動平台上的缺失,
很多過去的代碼,由於都是把byte 當作ansichar 處理的,到了移動平台上,這些代碼都跑不起來了。而且很難改造。
那么只有使用Tbytes 里替換傳統的ansistring. 因此對數組操作增加了這么多方法來解決這個傳統問題。
那現在問題來了,傳統的pos 功能卻沒加入,導致大量的是使用pos 的操作無法改造。
不知道會在xe? 里面加入?現在臨時的辦法就是自己做一個find(pos)函數來解決這個問題。
為了不與以后的pos 沖突,函數名就叫find, 功能是在一個數組里面查找另一個數組,並返回位置。
function Find(const sub, Buffer:TBytes): Integer; var N: Integer; begin N := Length(sub); if N>0 then for Result := low(Buffer) to high(Buffer)-(N-1) do if CompareMem(@Buffer[Result], sub, N) then exit; Result := -1; end;
這樣就可以用這個替換原來的ansistring 的pos 操作了。
其實也可以做成helper 更方便用。
TBytesHelper = record helper for Tbytes public procedure setlength(len:integer); function Find(const sub:TBytes): Integer; procedure add(const buff:TBytes); end; procedure TBytesHelper.add(const buff: TBytes); begin self:=self+buff; end; function TBytesHelper.Find(const sub: TBytes): Integer; var len: Integer; begin len:= Length(sub); if len>0 then for Result := low(self) to high(self)-(len-1) do if CompareMem(@self[Result], sub, len) then exit; Result := -1; end; procedure TBytesHelper.setlength(len: integer); begin System.setlength(self,len); end;